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

时间:2019-03-11 13:06:07

标签: php regex preg-match

该字符串可能每次都一行一行。

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

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

1 个答案:

答案 0 :(得分:2)

尝试通过以下正则表达式模式使用preg_match_all

town=\S+

这表示要匹配town=,后跟任意数量的 non 空格字符。然后在输出数组中提供匹配项。

$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
)