regex 正则表达式从一个单词开始直到特定的单词/字符/空格

ztyzrc3y  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(174)

字符串每次都可以是一行一行的。

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
  • 注意:我知道有很多方法可以实现这个任务,但我只想使用正则表达式。谢谢 *
6yjfywim

6yjfywim1#

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

w3nuxt5m2#

使用爆炸和空间爆炸。

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

j91ykkif

j91ykkif3#

使用explode()函数。

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

相关问题