提问人:Suneth Kalhara 提问时间:8/26/2021 最后编辑:brombeerSuneth Kalhara 更新时间:9/3/2021 访问量:344
PHP 在给定字符串的第二个单词后插入 br 标签
PHP insert br tag after 2nd Word of a Given String
问:
我正在尝试在给定字符串的第二个单词之后插入标签,但它裁剪了我的字符串中的一些单词,任何人都可以帮助修复此代码<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;
答:
2赞
Nero
8/26/2021
#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;
1赞
64Bit1990
8/26/2021
#2
使用$pos您可以选择标签的位置。<br/>
用于在第二个位置后添加标签$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;
1赞
jspit
8/26/2021
#3
使用preg_replace:
$new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);
评论