Dyl*_*lan 71 php string replace preg-replace
我需要删除字符串的子字符串,但只有当它位于字符串的END时.
例如,删除以下字符串末尾的"string":
"this is a test string" -> "this is a test "
"this string is a test string" - > "this string is a test "
"this string is a test" -> "this string is a test"
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?可能是某种preg_replace,但是如何?
Tim*_*per 112
你会注意到$字符的使用,它表示字符串的结尾:
$new_str = preg_replace('/string$/', '', $str);
Run Code Online (Sandbox Code Playgroud)
如果字符串是用户提供的变量,最好先运行它preg_quote:
$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);
Run Code Online (Sandbox Code Playgroud)
Skr*_*l29 22
如果子字符串具有特殊字符,则使用regexp可能会失败.
以下内容适用于任何字符串:
$substring = 'string';
$str = "this string is a test string";
if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));
Run Code Online (Sandbox Code Playgroud)
我为字符串的左右修剪写了这两个函数:
/**
* @param string $str Original string
* @param string $needle String to trim from the end of $str
* @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
* @return string Trimmed string
*/
function rightTrim($str, $needle, $caseSensitive = true)
{
$strPosFunction = $caseSensitive ? "strpos" : "stripos";
if ($strPosFunction($str, $needle, strlen($str) - strlen($needle)) !== false) {
$str = substr($str, 0, -strlen($needle));
}
return $str;
}
/**
* @param string $str Original string
* @param string $needle String to trim from the beginning of $str
* @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
* @return string Trimmed string
*/
function leftTrim($str, $needle, $caseSensitive = true)
{
$strPosFunction = $caseSensitive ? "strpos" : "stripos";
if ($strPosFunction($str, $needle) === 0) {
$str = substr($str, strlen($needle));
}
return $str;
}
Run Code Online (Sandbox Code Playgroud)
我想你可以使用一个正则表达式,它会匹配string,然后是字符串的结尾,再加上preg_replace()函数.
像这样的东西应该工作得很好:
$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);
Run Code Online (Sandbox Code Playgroud)
备注:
string 比赛......好吧...... string$指字符串的结尾有关更多信息,您可以阅读PHP手册的Pattern Syntax部分.