在最后一次出现任何白名单字符时截断字符串

问题描述 投票:0回答:3

我想使用正则表达式来删除最后一次出现的一些特殊符号之后的字符串。即我有绳子

Hello, How are you ? this, is testing

那么我需要这样的输出

Hello, How are you ? this

这些将是我的特殊符号

, : |

php regex replace truncate
3个回答
3
投票

当正常的字符串操作完全没问题时,为什么还要费心使用正则表达式呢?
编辑;注意到字符串中的

:
,
的行为不正确。
此代码将循环所有字符并查看哪个字符是最后一个并在那里对其进行子字符串化。如果根本没有“字符”,它将把 $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


1
投票

使用正则表达式将字符串(按特殊字符)拆分为数组并删除数组中的最后一个元素:

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

0
投票

preg_replace()
最适合此任务 - 它是单个本机函数调用,不需要使用循环或生成临时数组。

查找列出的字符之一,然后检查字符串中的其余字符是否不在同一列表中 - 这就是您如何知道找到最后出现的列出字符的方式。

代码:(演示

echo preg_replace('/[,:|][^,:|]*$/', '', 'Hello, How are you ? | this, is testing');
© www.soinside.com 2019 - 2024. All rights reserved.