【问题标题】:PHP insert br tag after 2nd Word of a Given StringPHP 在给定字符串的第二个单词之后插入 br 标记
【发布时间】:2021-10-26 08:01:45
【问题描述】:

我正在尝试在给定字符串的第二个单词之后插入 <br/> 标签,但它会裁剪我的字符串中的一些单词,任何人都可以帮助修复此代码

$pos = 1;
$string  = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
$new_array = array_slice($words, 0, $pos, true) +
    array($pos => '<br/>') +
    array_slice($words, $pos, count($words) - 1, true) ;
$new_string = join(" ",$new_array);
echo $new_string;

【问题讨论】:

    标签: php arrays string join slice


    【解决方案1】:

    您可以使用array_splice

    $pos = 1;
    $string  = 'Lorem Imsem Dollar Country';
    $words = explode(" ", $string);
    array_splice( $words, $pos, 0, '<br>' );
    $new_string = join(" ",$words);
    echo $new_string;
    

    【讨论】:

      【解决方案2】:

      使用 $pos 可以选择&lt;br/&gt; 标签的位置。

      使用$pos = 2在第二个位置后添加标签

      $pos = 2;
      $string  = 'Lorem Imsem Dollar Country';
      $words = explode(" ", $string);
      array_splice( $words, $pos, 0, '<br>' );
      $new_string = join(" ",$words);
      echo $new_string;
      

      【讨论】:

        【解决方案3】:

        使用 preg_replace:

        $new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多