Search code examples
phpregexregex-greedyword-boundaries

Match between whole word and partial word


My code is:

$tt = 'This is a tomato test';
preg_match('/is(.*)to/', $tt, $match);
print_r($match); 

From this I am trying to get " a toma" output only...but it is giving me:

Array
(
    [0] => is is a tomato
    [1] =>  is a toma
)

For this, regex how can I make it not display the extra "is" (the trailing letters of this) at the beginning of the output strings?


Solution

  • The simplest solution is to note that "this" includes the substring "is" so...

    $tt='This is a tomato test';
    $rr=preg_match('/ is(.*)to/',$tt,$match); // add a space before is.
    print_r($match); 
    

    And [1] will be "a toma"