Reputation: 175
I have a list with this structure
Boss: (test 23, of 2014)
Boss: (test 42, of 2015)
Boss: (test 70, of 2016)
How can I capture the numbers in the string and wrap then in spans? So the structure will end like this:
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>)
Upvotes: 0
Views: 36
Reputation: 25632
You can get away with this one-liner:
$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);
You might want to make this fault-tolerant regarding white space, i.e. use \s+
instead of hard coded spaces to allow for multiple whitespaces, tabs etc.
Upvotes: 1
Reputation: 239
This function can help here
step one:
preg_replace('# ([0-9]{2}),#','<span class="test_$1">$1</span>',$input);
step two:
preg_replace('# ([0-9]{4})#','<span class="year_$1">$1</span>',$input);
Upvotes: 2