Solved

How to Remove Characters from a String Using PHP

Posted on 2014-12-20
4
109 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 109

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 109

Expert Comment

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

Featured Post

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

810 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