php就像功能一样

Sud*_*dhi 2 php regex sed equivalent

我对bash shell上的sed非常熟悉,所以我这样做

cat $myfile | egrep $pattern | sed -e 's/$pattern/$replace/g'
Run Code Online (Sandbox Code Playgroud)

很多.很多次,我发现我需要在PHP中进行类似的"字符串解析".

所以我的问题很简单,sed -e 's/$pattern/$replace/g'PHP中的等价物是什么?

我知道preg_match,preg_replace,但我没有使用它们/根本不熟悉它们.我非常感谢PHP中的示例代码.(将a转换$var = '_myString'$newVar = 'getMyString')

tro*_*skn 8

这些preg_函数使用与Perl相同的regexp库,因此您应该在家中.还有语法的文档在这里.

例如:

sed -e 's/$pattern/$replace/g'
Run Code Online (Sandbox Code Playgroud)

会是这样的:

$output = preg_replace("/".$pattern."/", $replace, $input);
Run Code Online (Sandbox Code Playgroud)

最常见的是使用/as分隔符,但您可以使用其他字符,如果模式包含大量斜杠,则可能很有用,如url和xml标记的情况.你也可能觉得preg_quote有用.