正则表达式 - 获取匹配的索引

时间:2014-11-17 09:28:27

标签: regex text

我有崇高的文字或phpstorm。

我想通过regex replace更改此字符串:

Hello world

<span class="word1">Hello</span>
<span class="word2">world</span>

怎么做?

我的代码:

(\w+)

而不是$ index?

<span class="word$index">$1</span>

2 个答案:

答案 0 :(得分:0)

正则表达式:

^(\w+) (\w+)$

更换字符串:

<span class="word1">$1</span>\n<span class="word2">$2</span>

DEMO

答案 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)