正则表达式以一个单词开头,直到特定的单词/ char / space [复制]

问题描述 投票:0回答:3

这个问题在这里已有答案:

每次都可以逐行跟随字符串。

code=876 and town=87 and geocode in(1,2,3)
code=876 and town=878 and geocode in(1,2,3)
code=876 and town="878" and geocode in(1,2,3)
code=876 and town=8,43 and geocode in(1,2,3)
code=876 and town='8,43' and geocode in(1,2,3)
code=876 and town=-1 and geocode in(1,2,3)
code=876 and town=N/A and geocode in(1,2,3)

结果应该是preg_match

town=87
town=878
town="878"
town=8,43
town='8,43'
town=-1
town=N/A

注意:我知道有多种方法可以实现此任务,但我只想要正则表达式。谢谢

php regex preg-match
3个回答
2
投票

尝试使用preg_match_all,具有以下正则表达式模式:

town=\S+

这表示匹配town=后跟任意数量的非空白字符。然后在输出数组中提供匹配。

$input = "code=876 and town=87 and geocode in(1,2,3)";
$input .= "code=876 and town=878 and geocode in(1,2,3)";
$input .= "code=876 and town=\"878\" and geocode in(1,2,3)";
$input .= "code=876 and town=8,43 and geocode in(1,2,3)";
$input .= "code=876 and town='8,43' and geocode in(1,2,3)";
$input .= "code=876 and town=-1 and geocode in(1,2,3)";
$input .= "code=876 and town=N/A and geocode in(1,2,3)";
preg_match_all("/town=\S+/", $input, $matches);
print_r($matches[0]);

Array
(
    [0] => town=87
    [1] => town=878
    [2] => town="878"
    [3] => town=8,43
    [4] => town='8,43'
    [5] => town=-1
    [6] => town=N/A
)

2
投票

使用爆炸和爆炸空间。

foreach(explode(PHP_EOL, $str) as $line){
    echo explode(" ", $line)[2];
}

输出:

town=87
town=878
town="878"
town=8,43
town='8,43'
town=-1
town=N/A

https://3v4l.org/MOUhm


1
投票

使用explode()函数。

$str = "code=876 and town=87 and geocode in(1,2,3)";
echo explode(" and ",$str)[1];
© www.soinside.com 2019 - 2024. All rights reserved.