5

I am quite familiar with sed on bash shell, so I do

cat $myfile | egrep $pattern | sed -e 's/$pattern/$replace/g'

a lot. Quite a few times, I find that I need to do similar kind of "string parsing" inside PHP.

So my question is simple, what is the equivalent of sed -e 's/$pattern/$replace/g' in PHP ?

I know preg_match , preg_replace , but I haven't used them / not at all familiar with them. I would really appreciate sample code in PHP. (converting say a $var = '_myString' to $newVar = 'getMyString' )

wadkar
  • 960
  • 2
  • 15
  • 29
  • 1
    There is also str_replace() - when you don't need more advanced regexp. – EO2 Oct 14 '11 at 08:57
  • thanks @EO2 : I didn't think about str_replace() ! , will certainly try and avoid regex whenever I can with str_replace() . – wadkar Oct 14 '11 at 09:38

1 Answers1

11

The preg_ functions uses the same regexp library that Perl does, so you should be at home. There's documentation of the syntax here.

For example:

sed -e 's/$pattern/$replace/g'

Would be something like:

$output = preg_replace("/".$pattern."/", $replace, $input);

The most common is to use / as delimiter, but you can use other characters, which can be useful if the pattern contains lots of slashes, as is the case with urls and xml tags. You may also find preg_quote useful.

troelskn
  • 115,121
  • 27
  • 131
  • 155
  • thanks, I am going through preg_* PHP manual pages, and preg_quote seems a handy function. Can you point/explain the 'e' flag for PCRE ? And how to use it ? (I guess its there somewhere in the PHP manuals ...) – wadkar Oct 14 '11 at 09:17
  • I've never used the `e` modifier - I prefer using [`preg_replace_callback`](http://www.php.net/manual/en/function.preg-replace-callback.php), which semantically does the same thing. – troelskn Oct 14 '11 at 10:11
  • thanks, I will go through it, sounds much cleaner and simpler (writing a regex itself is a complex task, no need to add extra burden of `e` modifier) – wadkar Oct 18 '11 at 07:06
  • Remember that newer versions of php (5.3+) have support for anonymous functions, which are perfect for this case. – troelskn Oct 18 '11 at 10:34
  • yes, I know, aren't they called closures ? Or maybe I am wrong, as I faintly remember that Anonymous Functions and Closures are not exactly same. Thanks again. – wadkar Oct 18 '11 at 12:43
  • It's sort of the same thing, yes. A closure is the runtime binding of an anonymous function along with a capture of the stack. Think of an anonymous function as a class and a closure as an object. It's not exactly right, but close. – troelskn Oct 18 '11 at 20:50