echo $string
可以给出任何文字。仅替换字符串的末尾
如何删除字"blank"
,只有当它是的最后一个字?
因此,如果我们有像"Steve Blank is here"
这样的句子 - 不应该删除任何内容,否则如果句子是"his name is Granblank"
,那么应删除"Blank"
单词。
echo $string
可以给出任何文字。仅替换字符串的末尾
如何删除字"blank"
,只有当它是的最后一个字?
因此,如果我们有像"Steve Blank is here"
这样的句子 - 不应该删除任何内容,否则如果句子是"his name is Granblank"
,那么应删除"Blank"
单词。
你可以很容易地使用正则表达式。 \b
确保只有它是一个单独的词时才会被删除。
$str = preg_replace('/\bblank$/', '', $str);
尝试以下:
$str=trim($str);
$strlength=strlen($str);
if(strcasecmp(substr($str,($strlength-5),$strlength),'blank')==0)
echo $str=substr($str,0,($strlength-5))
不要使用preg_match
unlesss它不是必需的,PHP本身建议使用字符串函数在正则表达式功能,当比赛很简单。从preg_matc h手册页
ThiefMaster是相当正确的。不涉及结束行$
正则表达式字符的技术将使用rtrim。
$trimmed = rtrim($str, "blank");
var_dump($trimmed);
^这就是如果你想删除字符串的最后一个字符。如果你想删除的最后一个字:
$trimmed = rtrim($str, "\sblank");
var_dump($trimmed);
上Teez的回答变化:
/**
* A slightly more readable, non-regex solution.
*/
function remove_if_trailing($haystack, $needle)
{
// The length of the needle as a negative number is where it would appear in the haystack
$needle_position = strlen($needle) * -1;
// If the last N letters match $needle
if (substr($haystack, $needle_position) == $needle) {
// Then remove the last N letters from the string
$haystack = substr($haystack, 0, $needle_position);
}
return $haystack;
}
echo remove_if_trailing("Steve Blank is here", 'blank'); // OUTPUTS: Steve blank is here
echo remove_if_trailing("his name is Granblank", 'blank'); // OUTPUTS: his name is Gran
这个代码将取代“空白”无处不在,应该只需更换,如果它是字符串中的最后一次出现。 – Jasper 2012-01-05 23:54:33
错误。这就是'$'的用途。 – EboMike 2012-01-06 00:01:42
@Steve你试过这段代码吗?它适用于您建议的用例。仅当字符串末尾为空时,$表示匹配。虽然在你的具体用例中,正则表达式应该是/ blank $ /,因为你不关心字边界。 – Owen 2012-01-06 00:04:12