簡體   English   中英

查找字符串並替換單詞並刪除后續單詞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);

我只想有“大學”之前的單詞,並且可以是未定義數量的單詞。 因此,上面的內容類似於“ Example University%”。

我已經嘗試過str_replace,但這只是替換了出現的情況。

您可以使用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/zh/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."%";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM