Solved

How to Remove Characters from a String Using PHP

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

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 108

Expert Comment

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

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Button Click 11 25
PHP Sum Column in Table 3 27
Return data with AJAX, JQUERY and PHP 13 27
php connect() failed error 25 13
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…
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…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now