我对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'
)
最佳答案
preg_
函数使用与Perl相同的regexp库,因此您应该在家。有语法here的文档。
例如:
sed -e 's/$pattern/$replace/g'
将是这样的:
$output = preg_replace("/".$pattern."/", $replace, $input);
最常见的是使用
/
作为分隔符,但是您可以使用其他字符,如果该模式包含很多斜杠(如url和xml标记),这将很有用。您可能还会发现preg_quote
有用。
关于php - php sed之类的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7765067/