phpregexreplacetruncate

Truncate string on last occurrence of any whitelisted character


I would like use of regex to remove string after some special symbols on last occurrence. i.e. I am having string

Hello, How are you ? this, is testing

then I need output like this

Hello, How are you ? this

and these will be my special symbols , : |


Solution

  • Why bother with a regex when normal string operations are perfectly fine?
    EDIT; noticed how it not behave correctly with both : and , in the string.
    This code will loop all chars and see which is last and substring it there. If there is no "chars" at all it will set $pos to strings full lenght (output full $str).

    $str = "Hello, How are you ? this: is testing";
    $chars = [",", "|", ":"];
    $pos =0;
    foreach($chars as $char){
        if(strrpos($str, $char)>$pos) $pos = strrpos($str, $char);
    }
    if($pos == 0) $pos=strlen($str);
    echo substr($str, 0, $pos);
    

    https://3v4l.org/XKs2Z