简体   繁体   English

正则表达式在最后一次出现特殊字符后删除字符串

[英]Regex remove string after special characters on last occurance

I would like use of regex to remove string after some special symbols on last occurance. 我想使用regex在上次出现某些特殊符号后删除字符串。 ie i am having string 即我有绳子

Hello, How are you ? this, is testing

then i need output like this 那我需要这样的输出

Hello, How are you ? this

as these will be my special symbols , : : | 因为这些将是我的特殊符号, : : |

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). 如果根本没有“字符”,它将把$ pos设置为字符串完整长度(输出完整$ 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 https://3v4l.org/XKs2Z

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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM