2016-10-18 78 views
0

兩個部分我有一個清單,這個結構捕捉相同的字符串與PHP

Boss: (test 23, of 2014) 

Boss: (test 42, of 2015) 

Boss: (test 70, of 2016) 

我怎樣才能捕捉到數字字符串中和跨度然後包?所以結構將結束這樣的:

Boss: (test <span class="test_23">23</span>, of <span class="year_2014">2014<span>) 

Boss: (test <span class="test_42">42</span>, of <span class="year_2014">2015<span>) 

Boss: (test <span class="test_70">70</span>, of <span class="year_2016">2014<span>) 
+2

開始與'的preg_replace()' – nogad

回答

2

此功能可以幫助這裏

步驟一:

preg_replace('# ([0-9]{2}),#','<span class="test_$1">$1</span>',$input);

步驟二:

preg_replace('# ([0-9]{4})#','<span class="year_$1">$1</span>',$input);

1

你可以逃避這一行:

$input = "Boss: (test 23, of 2014)"; 

$output = preg_replace(
    '/Boss: \(test (\d+), of (\d{4,4})\)/', 
    'Boss: (test <span class="test_$1">$1</span>, of <span class="year_$2">$2<span>)', 
    $input); 

你可能想使這對於容錯空白,即使用\s+,而不是硬編碼的空間以允許多個空格,製表符等