如何使用 preg_replace 修剪特定值周围的所有内容
我试图找到一个与模式匹配的值 X:
<span class="line-item-quantity-raw">X</span>
一旦获得该值,我想修剪它周围的所有其他内容。虽然我知道我可以使用 preg_match 执行此操作只是为了获取值并设置变量,但我很好奇为什么我无法使用 preg_match 使原始方法发挥作用。
$footer = '<div class="line-item-summary">
<div class="line-item-quantity">
<span class="line-item-quantity-raw">1</span>
<span class="line-item-quantity-label">item</span>
</div>
<div class="line-item-total">
<span class="line-item-total-label">Total:</span>
<span class="line-item-total-raw">$1,500.00</span>
</div>
</div>';
$pattern = '/.*<span class="line-item-quantity-raw">(\d+)<\/span>.*/';
$replace = '($1) -';
$footer = preg_replace($pattern, $replace, $footer);
不幸的是,这似乎只删除了 $pattern
中指定的跨度标签,但是 $pattern
边缘的额外标记,例如 .*仍然被保留。
在测试页面中运行我的代码很烦人,例如 http://www.solmetra.com/scripts /regex/index.php 似乎可以工作,只是不是我上面的 php 代码。
I'm attempting to find a value X, which matches the pattern:
<span class="line-item-quantity-raw">X</span>
Once I've got the value, I want to trim everything else around it. While I know I could do this with preg_match just to get the value and set the variable, I'm quite curious as to why I can't get my original method with preg_match to function.
$footer = '<div class="line-item-summary">
<div class="line-item-quantity">
<span class="line-item-quantity-raw">1</span>
<span class="line-item-quantity-label">item</span>
</div>
<div class="line-item-total">
<span class="line-item-total-label">Total:</span>
<span class="line-item-total-raw">$1,500.00</span>
</div>
</div>';
$pattern = '/.*<span class="line-item-quantity-raw">(\d+)<\/span>.*/';
$replace = '($1) -';
$footer = preg_replace($pattern, $replace, $footer);
Unfortunately this only seems to strip out the span tags as specified in the $pattern
however the extra markup on the edges of the $pattern
such as .*
is still being kept.
Annoyingly running my code in a test page such as http://www.solmetra.com/scripts/regex/index.php seems to work, just not my code above in php.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
.
默认不匹配换行符。要使.
跨越多行,需要添加修饰符s
:http://php.net/manual/en/reference.pcre.pattern .modifiers.php
This is because
.
is not matching by default line breaks. To make.
span multiple lines, you need to add the modifiers
:http://php.net/manual/en/reference.pcre.pattern.modifiers.php
默认情况下,点不匹配换行符。
如果您使用
/s
修饰符,那么它将匹配它们(以及字符串的整个其余部分,这可能是也可能不是您想要的)。By default, the dot does not match newlines.
If you use the
/s
modifier, then it will match them (and the entire rest of the string, which may or may not be what you want).