php就像功能一样

时间:2011-10-14 08:37:52

标签: php regex sed equivalent

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

cat $myfile | egrep $pattern | sed -e 's/$pattern/$replace/g'
很多。很多次,我发现我需要在PHP中进行类似的“字符串解析”。

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

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

1 个答案:

答案 0 :(得分:8)

preg_函数使用与Perl相同的正则表达式库,因此您应该在家。有文档here的文档。

例如:

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

会是这样的:

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

最常见的是使用/作为分隔符,但您可以使用其他字符,如果模式包含大量斜杠,则可能很有用,例如urls和xml标记。您可能还会发现preg_quote有用。