Search code examples
phpregexpreg-match

how to exclude a string from php regex search


I want to exclude the as word from abc.id as odusing preg_match(); Could anyone help me what will be the pattern?

Desired result is:

abc.id as od

Hightlighed as the selection and as is excluded from search.


Solution

  • You can use the following regex pattern to select the string :

    (.*?)(?:\sas\s)(.*?)$
    

    ­

    input        >>  abc.id as od
    regex search >>  (.*?)(?:\sas\s)(.*?)$
    replace with >>  $1$2
    output       >>  abc.idod
    

    see demo / explanation

    PHP

    $re = '/(.*?)(?:\sas\s)(.*?)$/';
    $str = 'abc.id as od';
    $subst = '$1$2';
    $result = preg_replace($re, $subst, $str);
    echo $result;