Solved

How to Remove Characters from a String Using PHP

Posted on 2014-12-20
4
112 Views
Last Modified: 2014-12-22
I know there is a much better way to do this.  I have an input string and people sometimes hit the wrong character when they're trying to enter a word.

If the input string is "myword\" or "]myword" or "/myword"  (without quotes) I need it converted to: "myword"

Using long hand PHP code, I get what I want this way. But I know there's a much better way. Please inform me oh wise ones...

$rawtext = "myword\";
$value = str_replace("\\", "", $value); 
$value = str_replace("/", "", $value); 
$value = str_replace("]", "", $value); 
die ("Rawtext starts as [".$rawtext."] outputs a value of [".$value."]");

Open in new window


This will display: Rawtext starts as [myword\] outputs a value of [myword]

Thanks.
0
Comment
Question by:pkonstan1
  • 2
4 Comments
 
LVL 58

Assisted Solution

by:Gary
Gary earned 100 total points
ID: 40511334
Depends on what characters you want to allow

<?php
$rawtext = "[ My word/";

$fixed_text = preg_replace("/[^\w ]/","",$rawtext);

echo $fixed_text;

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 40511524
As with most things in programming, the quality of the answers you get is directly related to the quality of the test data you provide.  Do you want to allow hyphenated words?  How about common punctuations like Dr. Smith?  Sometimes the information may need to contain numbers or special characters.  That's why I usually recommend setting up a test case, such as described in this article.  You can make an array of test strings and try them all against various redaction strategies to see what give you the best set of outputs.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html

To learn more about regular expressions, you might start your adventure here.  Don't be impatient with yourself; it's nearly a semester of college work before you can master this pseudo-language that is almost all punctuation!
http://www.regular-expressions.info/tutorial.html

PHP has some online documentation here (do not use POSIX)
http://php.net/manual/en/book.pcre.php
http://php.net/manual/en/reference.pcre.pattern.syntax.php

You may find that a single regular expression is not able to meet all of your requirements.  In these cases a separate function may make more sense - you can use two or more regex or other filtering rules and still only need to write one line of procedural code to effect the desired changes.

Please see: http://iconoun.com/demo/temp_pkonstan1.php
I find that when I write regular expressions, it's helpful to write in this one-line style so I can add comments to explain what I was thinking.  It's also easy to change the regex when you write it in this expanded way.

<?php // demo/temp_pkonstan1.php
error_reporting(E_ALL);
echo '<pre>';

// SET UP TEST CASES - AS MANY AND VARIED AS YOU WANT
$testcases = array
( 'myword{'
, ']myword'
, '/myword'
, 'This is a test of the Emergency Launch System.'
, 'My phone number is 703-346-0600'
)
;

// SET UP REGULAR EXPRESSIONS OR FUNCTION CALLBACKS
$regex
= '#'              // REGULAR EXPRESSION DELIMITER
. '['              // START OF CHARACTER CLASS
. '^'              // NEGATION: MATCH NONE OF THESE CHARACTERS
. 'A-Z'            // ALPHABET
. ' '              // SPACE(S)
. '-.'             // PUNCTUATION (MAY WANT MORE HERE)
. ']'              // END OF CHARACTER CLASS
. '#'              // REGEX DELIMITER
. 'i'              // FLAGS: CASE-INSENSITIVE
;

// RUN THE TESTS
foreach ($testcases as $string)
{
    $new = preg_replace($regex, NULL, $string);
    echo PHP_EOL . "$string TURNS INTO: <b>$new</b>";
}

Open in new window

0
 

Author Comment

by:pkonstan1
ID: 40513526
Ray,

Thanks.  That's one of the best explanations I've ever had for how that works.

I actually set it up as a function so that I can use it multiple places.

function charStrip($txtIn, $keep) {
	// $txtIn is the raw text, 
	// keep uses thes options A=Alphabet Upper, a=Alpha Lower, 9=Numbers 
	//  then all other is the actual characters, spaces, period, dashes...
	// SET UP REGULAR EXPRESSIONS OR FUNCTION CALLBACKS
	$regex
		= '#'  // REGULAR EXPRESSION DELIMITER
		. '['  // START OF CHARACTER CLASS
		. '^'; // NEGATION: MATCH NONE OF THESE CHARACTERS
		for ($z = 0; $z < strlen($keep); $z++) {
			$cur = substr($keep,$z,1);
			switch ($cur) {
				case "A" : $regex .= 'A-Z'; break; // ALPHABET UPPER
				case "a" : $regex .= 'a-z'; break; // ALPHABET LOWER
				case "9" : $regex .= '0-9'; break; // NUMBERS
				default : $regex .= $cur;  // other characters
			} // switch (substr($keep,$z,0)) {
		} // for ($i = 0; $i <= 99; $i++)	
	$regex .= ']'              // END OF CHARACTER CLASS
		. '#'              // REGEX DELIMITER
		#. 'i'              // FLAGS: CASE-INSENSITIVE
		;
	return preg_replace($regex, NULL, $txtIn);		
} // function charStrip($txtIn, $keep) {

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 40514234
Lookis good.  Thanks for the points, and thanks for using E-E, ~Ray
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
php56-php-mcrypt for rhel7 php56 1 101
What if i make webbased alternative for MS Access 5 101
check mysql insert 12 39
PHP encrypted string and passing to a ASP Page 12 38
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question