正则表达式将匹配替换为匹配 +插件
我想替换不区分大小写的 mix:
text StmiXx and some more mIxx text
在正则表达式替换之后:
text St<font color="red">miX</font>x and some more <font color="red>mIx</font> text
代码:
$string = "text StmiXx and some more mIxx text";
$pattern = "/mix/i";
$replacement = "<font color=\"red\">match</font>";
echo preg_replace($pattern, $replacement, $string);
如何使用正则表达式来完成此操作?我也想用 (Linux)sed 尝试一下,或者还有一种使用egrep、grep 的方法。
egrep 有一个选项 --color=always 但没有自定义突出显示。
I would like to replace case-insensitive let's say mix:
text StmiXx and some more mIxx text
after regex replacement:
text St<font color="red">miX</font>x and some more <font color="red>mIx</font> text
code:
$string = "text StmiXx and some more mIxx text";
$pattern = "/mix/i";
$replacement = "<font color=\"red\">match</font>";
echo preg_replace($pattern, $replacement, $string);
How can this be done with regex? I also would like to try this with (Linux)sed or is there also a way with egrep, grep.
egrep has an option --color=always but not custom highlight.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你很接近!以下是在 PHP 中执行此操作的方法:
在模式中,括号可用于捕获内容(组)。然后您可以通过重复括号的数量来引用该组。在这种情况下,我们只有一组。这就是为什么在替换中我使用
$1
来引用我们模式中唯一的捕获组。You were close! Here is how you can do it in PHP:
In the pattern the parentheses can be used to capture the content (group). Then you can reference the group by the number of repeated parentheses. In this case we have only one group. That's why in the replacement I used
$1
to reference the only capture group we have in our pattern.编辑:
要执行替换并仅打印匹配的行:
并且要仅获取前 N 行,您可以将其通过管道传输到 head 或:
Edit:
To perform the substitution and only print the lines that match:
And to get only the first N lines, you can pipe this to head or to:
必须凝视一分钟才能真正弄清楚代码内部是否有问题:)
$1 代表模式在 () 中找到的第一个东西
例如,如果您出于某种原因想将其更改为 m-ix,您可以这样这:
Had to stare a minute to actually figure out if something was wrong inside the code :)
$1 represents the first thing the pattern finds inside ()
For instance, if you want to change it to m-ix for some reason, you could so like this: