查找字符串并替换单词,然后删除后面的单词PHP


Find String and Replace word and remove subsequent words PHP

我试图删除php中字符串中某个单词后面的单词。

我用这个来代替:

$text = "Example University School of Science";
$oldUni = "University";
$newUni = "University%";
$text = str_replace($oldUni , $newUni , $text);

我只想要"大学"前面的单词,它可以是未定义的单词数量。因此,上面看起来像"示例大学%"。

我试过str_replace,但它只是取代了出现的情况。

Abu您可以使用nevermind的代码,或者如果您使用的是PHP>=5.3.0,则可以使用以下代码:-

$text = "Example of the University School of Science";
$oldUni = "University";
$user = strstr($text, $oldUni, true);
echo $user . $oldUni .'%'; // prints name

虽然strstr函数以前确实存在,但第三个参数(true)仅在PHP 5.3.0 中添加

参考:-http://php.net/manual/en/function.strstr.php

试试这个:

$array = explode ($text, "University");
$newText = $array[0];

希望能有所帮助:)

$text = "Example University School of Science";
$var="University";
$pos=stripos($text,$var);

$text_new=substr($text,0,$pos+strlen($var));
echo $text_new."%";