Search code examples
regexpreg-match

Regular expression to match from the end of a match condition


I want to match from the end of a result from a or condition in regular expression.

$a = 'SI-#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER';
$pat = '/^(?(?=SI)(?<matchfromend>[A-Z]+$)|(?<else>.*))/';

i want to match CANCEL BY 5 PM - RQST-NO FEATHER only if string starts from SI-

Any suggestion ??

Thanks


Solution

  • Your (?(?=SI)(?<matchfromend>[A-Z]+$) regex part does not consume arbitrary characters from the beginning of the string up to the end (?<matchfromend>[A-Z]+$ pattern.

    You can use the following regex:

    '~^(?(?=SI).*#¤(?<matchfromend>.+$)$|(?<else>.*))~'
    

    See the regex demo

    Explanation:

    • ^ - start of string
    • (?(?=SI).*#¤(?<matchfromend>.+$)$|(?<else>.*)) - a conditional:
      • If SI appears at the start ((?=SI)) match 0+ characters other than a newline up to the last , and capture 1+ characters other than a newline up to the end of the string into Group "matchfromend"
      • If there is no SI at the start, match 0+ characters other than a newline up to the end of the line.

    Another NON-REGEX approach

    Check if a string starts with SI and if yes, explode with and get the last item. If not, use the whole string.

    See IDEONE demo:

    $str = "SI-#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER"; // => CANCEL BY 5 PM - RQST-NO FEATHER
    //$str = "#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER"; 
    $res = $str;
    if (strrpos($str, "SI", -strlen($str)) !== false) { // starts with SI
        $arr = explode("#¤", $str);
        if (!empty($arr)){
            $res  = array_pop($arr);
        }
    }
    echo $res;