?
Solved

How to Remove Characters from a String Using PHP

Posted on 2014-12-20
4
Medium Priority
?
127 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 58

Assisted Solution

by:Gary
Gary earned 400 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 111

Accepted Solution

by:
Ray Paseur earned 1600 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 111

Expert Comment

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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

762 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