PHP查找并替换字符串的一部分

use*_*349 0 php string replace

我有一个输入字符串.格式如下:

This;is;my;long;string
Run Code Online (Sandbox Code Playgroud)

使用PHP获取此输出字符串的任何快速解决方案(很多字符串):

This;is;my;long
Run Code Online (Sandbox Code Playgroud)

我需要删除这个附录: ;string

  • 我不知道附录的长度:;这里有任何字母.

谢谢!

Mat*_*att 5

如果您一直;用作分隔符,则可以explode()使用字符串,删除最后一个索引,然后使用implode()以下命令重新加入字符串:

$str    = "This;is;my;long;string";
$strArr = explode(";", $str);

unset($strArr[count($strArr) - 1]);
$newStr = implode(";", $strArr);
Run Code Online (Sandbox Code Playgroud)

UPDATE

为了使这个适用于任何可搜索的字符串,您可以使用array_keys():

$str             = "This;is;my;long;string";
$strArr          = explode(";", $str);
$searchStr       = "string";
$caseSensitive   = false;
$stringLocations = array_keys($strArr, $searchStr, $caseSensitive);

foreach ($stringLocations as $key) {
    unset($strArr[$key]);
}
$newStr = implode(";", $strArr);
Run Code Online (Sandbox Code Playgroud)

或者,甚至更快,您可以使用array_diff():

$str       = "This;is;my;long;string";
$strArr    = explode(";", $str);
$searchStr = array("string");
$newArray  = array_diff($searchStr, $strArr);
$newStr    = implode(";", $newArray);
Run Code Online (Sandbox Code Playgroud)