我想使用正则表达式删除字符串后,一些特殊的符号在最后出现。也就是说我有绳子
Hello, How are you ? this, is testing那么我需要像这样的输出
Hello, How are you ? this因为这些将是我的特殊符号, : : |
发布于 2017-09-28 07:56:55
当正常的字符串操作非常好的时候,为什么还要费心使用正则表达式呢?
编辑;注意到字符串中的:和,的行为都不正确。
这段代码将循环所有字符,查看哪个是最后一个,并在那里进行子字符串。如果根本没有"chars“,它将将$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);发布于 2017-09-28 08:14:40
使用regex将字符串(按特殊字符)拆分为数组,并删除数组中的最后一个元素:
<?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);
?>https://stackoverflow.com/questions/46463640
复制相似问题