如何取出字符串的特定部分并将剩余字符串保存在变量中


How do I take out a specific part of a string and save the remaning string in a variable?

我想在字符串中查找子字符串,如果找到,我想取出找到的子字符串。
我正在字符串helloworld中寻找hello这个词。
如果找到子字符串,我想取出该子字符串并将剩余的剩余部分保存在变量中。

$newVar = 'world';我有一个在字符串中查找子字符串的代码:

$originalStr = 'helloworld'
$strToCompare = 'hello';
if (stristr($originalStr, $strToCompare)){
  //take out the string that was found and save the rest in a variable.
    $newVar = 'world';
}

您可以使用 strpos 函数,该函数用于查找一个字符串在另一个字符串中的出现:

$originalStr = 'helloworld';
$strToCompare = 'hello';
if (strpos($originalStr, $strToCompare)!== FALSE) {
    $newVar = str_replace($strToCompare,'',$originalStr);
}

请注意,您需要与!==运算符进行比较 NOT !=