gpt4 book ai didi

PHP 正则表达式将两个斜杠 (//) 替换为新行

转载 作者:可可西里 更新时间:2023-11-01 00:48:35 24 4
gpt4 key购买 nike

我在这里尝试做的是获取一个通常可能包含代码注释的字符串,并将其替换为其他内容,尤其是将其包装在其他内容中。我很确定 preg_replace 函数可以在这里工作,但我不知道从哪里开始使用 Regex。例如:

Hello world //this is a comment
Testing //not testing
Test again

会变成

Hello world %//this is a comment%
Testing %//not testing%
Test again

preg_replace('???', '%$1%', $matches); 是我自己能想到的,非常感谢任何帮助!

最佳答案

preg_replace('~//.*$~m', '', $str);

这将删除 // 之后(包括)到行尾的所有内容

http://ideone.com/Xhmpd

preg_replace('~//.*$~m', 'foo \\0 bar', $str);

这将用 foo bar 将它们包裹起来

http://ideone.com/IqkWM

关于PHP 正则表达式将两个斜杠 (//) 替换为新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272646/

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