简体   繁体   English

PHP正则表达式首先提取嵌套表达式然后是外部表达式

[英]PHP regular expressions to extract a nested expression first then the outer expression

I am having a problem with bit of code. 我遇到了一些代码问题。

This is the code 这是代码

$test ='<number>1<number>2</number>3</number>';

$i=0;
$find[$i]="#<number>(.*)</number>#is";
$replace[$i]="5";

$i++;
$find[$i]="#<number>(.*)</number>#is";
$replace[$i]="$1";


echo htmlentities(preg_replace($find, $replace, $test));

At the moment this displays just the numnber 5 in the results. 目前,这只显示结果中的numnber 5。 But i want it to display 153 Does anyone know what I am doing wrong? 但我想让它显示153有谁知道我做错了什么? thanks 谢谢

Yes, since .* matches everything (including the tags), you're matching too much. 是的,因为.*匹配所有东西(包括标签),你匹配得太多了。 If you restrict your regex not to match across tag boundaries by preventing it from matching angle brackets, you get the desired result: 如果通过阻止正则表达式匹配尖括号来限制正则表达式不匹配标记边界,则会得到所需的结果:

$test ='<number>1<number>2</number>3</number>';

$i=0;
$find[$i]="%<number>([^<>]*)</number>%is";
$replace[$i]="5";

$i++;
$find[$i]="%<number>([^<>]*)</number>%is";
$replace[$i]="$1";

将第一个替换模式更改为:

$find[$i] = "#<number>\d+<number>(.*)</number>\d+</number>#is";
$s ='<number>1<number>2</number>3</number>'; 
echo preg_replace('#<number>(\d+)<number>\d+</number>(\d+)</number>#', "$1 5 $2", $s);

Test code here . 在这里测试代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM