想要处理一组字符串,并从每个字符串的末尾删除一些以“myEnding”结尾的内容(如果存在)。最简单的方法是什么?我知道使用正则表达式可以实现所有功能,但这似乎是一个简单的任务。我想知道是否存在更简单的工具来完成这项任务。谢谢,Gidi。
我会选择使用 preg_replace 来解决这个问题。
$output = preg_replace('/myEnding$/s', '', $input);
$output = preg_replace('/' . preg_quote($myEnding) . '$/s', '', $input);
- marcguyer试试这个:
$s = "foobarmyEnding";
$toRemove = "myEnding";
$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
$s = substr($s, 0, -$len);
}
rtrim
http://php.net/manual/zh/function.rtrim.php
$str = "foobarmyEnding";
$str = rtrim($str, 'myEnding');
// str == "foobar"
ltrim 是用于字符串开头的同款函数 http://php.net/manual/en/function.ltrim.php
如果你需要修改字符串的开头或结尾,你也可以使用 str_replace 将搜索项替换为空字符串,但它比 rtrim/ltrim 慢。
rtrim
的第二个参数是要删除的字符列表,而不是整个字符串。 - TaZrtrim
函数作为字符列表的一部分。 - TaZ
s($str)->replaceSuffix('myEnding')
很有用,这个函数可以在这个独立库中找到。 - caw