-2

The string could be as following line by line every time.

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)

The result should be with preg_match

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

Note: I know there are various ways to achieve this task but I want to regex only. Thanks

zarpio
  • 10,380
  • 8
  • 58
  • 71
  • 1
    Why do you need a regex for this? strpos and substr is pretty sufficient for this task. – maio290 Mar 11 '19 at 13:07
  • Yes, I know. But want to achieve this with regex, please answer the best solution. – zarpio Mar 11 '19 at 13:09
  • 2
    I won't argue with you which method is the best one - but if you're having trouble writing a regex, you may consider using a method you fully understand. – maio290 Mar 11 '19 at 13:15

3 Answers3

2

Try using preg_match_all, with the following regex pattern:

town=\S+

This says to match town= followed by any number of non whitespace characters. The matches are then made available in an output array.

$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
)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Use explode and explode on space.

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

Outputs:

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

https://3v4l.org/MOUhm

Andreas
  • 23,610
  • 6
  • 30
  • 62
1

Use explode() function.

$str = "code=876 and town=87 and geocode in(1,2,3)";
echo explode(" and ",$str)[1];
nice_dev
  • 17,053
  • 2
  • 21
  • 35