Vipul L.
Vipul L.

Reputation: 595

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 , : |

Upvotes: 0

Views: 208

Answers (3)

mickmackusa
mickmackusa

Reputation: 48051

preg_replace() is best suited for this task -- it is a single native function call that doesn't need to use a loop or generate a temporary array.

Seek one of the listed characters, then check that none of the remaining characters in the string are in that same list -- this is how you know you found the last occurring listed character.

Code: (Demo)

echo preg_replace('/[,:|][^,:|]*$/', '', 'Hello, How are you ? | this, is testing');

Upvotes: 0

Kevin HR
Kevin HR

Reputation: 249

Use regex to split string (by special characters) into an array and remove the last element in array:

<?php
$string = "Hello, How are you ? this, is testing";
$parts = preg_split("#(\,|\:|\|)#",$string,-1,PREG_SPLIT_DELIM_CAPTURE);
$numberOfParts = count($parts);
if($numberOfParts>1) {
    unset($parts[count($parts)-1]); // remove last part of array
    $parts[count($parts)-1] = substr($parts[count($parts)-1], 0, -1); // trim out the special character
}
echo implode("",$parts);
?>

Upvotes: 1

Andreas
Andreas

Reputation: 23968

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

Upvotes: 3

Related Questions