Regular Expressions - String search and replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bucky
Forum Newbie
Posts: 2
Joined: Sun Jan 12, 2003 6:20 am

Regular Expressions - String search and replace

Post by Bucky »

ok, im pretty newbish to regular expression and i'd like some help.

I want to read a string for the following characters:
< > | [ ] - + \ /

Then replace those characters with a NULL or white space.

Anyhelp?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

try this one

Code: Select all

<?php
$testtext = '<>|[]-+\/';
$pattern = '![<>|\[\]\-+\\\/]!';
echo preg_replace($pattern, '', $testtext);
?>
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

If you just want to get rid of those particular characters then it is not really necessary to use regular expressions, instead you could just use str_replace():

Code: Select all

$original = '<>|[]-+\/';
$from = array('<', '>', '|', '[', ']', '-', '+', '\'', '/');
$adjusted = str_replace($from, '', $original);
Mac
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

way too simple :D

no, twigletmac is right. Although we're talking about a fraction of a second, str_replace is also faster than preg_replace in this (not only this) case ;)
Bucky
Forum Newbie
Posts: 2
Joined: Sun Jan 12, 2003 6:20 am

Thx alot

Post by Bucky »

Hey thx everyone, though it was an easy solution (which really made me feel like an idiot) i've bee strugling with the problem for a good 4 days. Usually im not that bad of a php guy..ahh well. Could anyone reccommend a good regular expresion tutorial? Just to find all the good stuff on it..thx in advance.
glo-wurm
Forum Newbie
Posts: 13
Joined: Mon Jan 13, 2003 2:07 pm
Location: Naples, FL

Post by glo-wurm »

Here are a couple pretty good regex tutorial links that I had laying around...

http://japhy.perlmonk.org/book/
http://www.perldoc.com/perl5.6/pod/perlre.html

and as always, there is the PHP manual's documentation for regexes...
http://www.php.net/manual/en/pcre.pattern.syntax.php
Post Reply