我有崇高的文字或phpstorm。
我想通过regex replace更改此字符串:
Hello world
到
<span class="word1">Hello</span>
<span class="word2">world</span>
怎么做?
我的代码:
(\w+)
而不是$ index?
<span class="word$index">$1</span>
答案 0 :(得分:0)
答案 1 :(得分:0)
试试这个
$re = "/\\w+/m";
$str = "Hello world Hello2 world2";
preg_match_all($re, $str, $matches);
var_dump( $matches);
$out="";
if( count($matches[0])>0) foreach($matches[0] as $k=>$v){
$id=$k+1;
$out .= "<span class=\"word$id\">$v</span>\n";
}
var_dump($out);
<强>输出:强>
array (size=1)
0 =>
array (size=4)
0 => string 'Hello' (length=5)
1 => string 'world' (length=5)
2 => string 'Hello2' (length=6)
3 => string 'world2' (length=6)
string '<span class="word1">Hello</span>
<span class="word2">world</span>
<span class="word3">Hello2</span>
<span class="word4">world2</span>
' (length=134)