How to Remove Characters from a String Using PHP

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.
Paul KonstanskiProject SpecialistAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GaryCommented:
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
Ray PaseurCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Paul KonstanskiProject SpecialistAuthor Commented:
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
Ray PaseurCommented:
Lookis good.  Thanks for the points, and thanks for using E-E, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.