gpt4 book ai didi

php - php sed之类的功能

转载 作者:行者123 更新时间:2023-12-04 07:50:21 25 4
gpt4 key购买 nike

我对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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com