【问题标题】:Regex - How to replace the last 3 words of a string with PHP正则表达式 - 如何用 PHP 替换字符串的最后 3 个单词
【发布时间】:2014-04-24 15:17:01
【问题描述】:

试图将最后 3 个单词包含在 <span> 标记中

$str = 'Lorem ipsum dolor sit amet';
$h2 = preg_replace('/^(?:\w+\s\w+)(\s\w+)+/', '<span>$1</span>', $str);

【问题讨论】:

    标签: php regex


    【解决方案1】:

    这里是:

    $h2 = preg_replace('/(\w+\s\w+\s\w+)$/', '<span>$1</span>', $str);
    

    因为它的最后三个单词,所以让左边(从头开始)打开以进行匹配。

    【讨论】:

      【解决方案2】:

      Sabuj Hassan 将 数字和 _ 也视为单词的一部分,因此请在有意义的情况下使用它。

      假设“单词”是由空格分隔的字母

      $str = 'Lorem ipsum dolor sit amet';
      $h2 = preg_replace('/([a-z]+ [a-z]+ [a-z]+)$/i', '<span>$1</span>', $str);
      
      echo $h2;
      

      如果您希望将任何非空格视为一个单词,那么:

      $h2 = preg_replace('/(\S+ \S+ \S+)$/', '<span>$1</span>', $str);
      

      【讨论】:

        【解决方案3】:

        如果您将单词定义为以单个空格为界,则根本没有理由在这里使用正则表达式。相反,您可以使用基本的字符串操作来获得所需的结果。

        $str = ...; // your input string
        $words_with_offsets_in_key = str_word_count($str, 2);
        $word_count = count($word_offsets);
        if($word_count >= 3) {
            // we have at least 3 words
            // find offset of word three from end of array of words
            // grab third item from end of array
            $third_word_from_end = array_slice($words_with_offsets_in_key, $word_count - 3, 1);
            // inspect its key for offset value in original string
            $offset = key($third_word_from_end);
            // insert span into string
            $str = substr_replace ( $str , '<span>' , $offset, 0) . '</span>';
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-13
          • 2021-11-16
          • 1970-01-01
          • 2017-06-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多