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'
)
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.