【问题标题】:Find String and Replace word and remove subsequent words PHP查找字符串并替换单词并删除后续单词 PHP
【发布时间】:2014-11-01 15:49:18
【问题描述】:

我正在尝试在 php 中删除字符串中某个单词之后的单词。

我用这个来代替:

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

我只想拥有“大学”之前的单词,它可以是未定义的单词数。所以上面看起来像“Example University%”。

我尝试了 str_replace 但这只是替换了出现。

【问题讨论】:

    标签: php replace preg-replace


    【解决方案1】:

    您可以使用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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      希望有帮助:)

      【讨论】:

        【解决方案3】:
        $text = "Example University School of Science";
        
        $var="University";
        
        $pos=stripos($text,$var);
        
        
        $text_new=substr($text,0,$pos+strlen($var));
        
        echo $text_new."%";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-01-18
          • 2021-02-15
          • 1970-01-01
          • 2019-01-18
          • 2023-01-26
          • 2018-02-06
          • 1970-01-01
          相关资源
          最近更新 更多