正则表达式以一个词开头直到特定 word/char/space

Regex start with a word till specific word/char/space

字符串每次都可以如下一行。

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

注意:我知道有多种方法可以完成此任务,但我只想使用正则表达式。谢谢

尝试使用 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
)

在 space 上使用爆炸和爆炸。

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

使用explode()函数。

$str = "code=876 and town=87 and geocode in(1,2,3)";
echo explode(" and ",$str)[1];