php sed 类似功能
我对 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'
)
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'
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
preg_
函数使用与 Perl 相同的正则表达式库,因此您应该很熟悉。 此处有语法文档。例如:
类似于:
最常见的是使用
/
作为分隔符,但您可以使用其他字符,如果模式包含大量斜杠(如 url 的情况),这会很有用和 xml 标签。您可能还会发现preg_quote
很有用。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:
Would be something like:
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 findpreg_quote
useful.