PHP regex to replace links with some tokens

时间:2015-07-28 15:55:47

标签: php regex

I'm looking at some HTML that has embedded audio-playback links like that:

...<input type="button" onclick="return play('filename', 'title');" class="playlink" />...

I'm trying to programmatically replace that with tokens in this format:

{a:filename:title}

But something's not working right. Could someone look at it:

<?php

$src = 'aaaaa<input type="button" onclick="return play(\'hellofile\', \'hellotitle\');" class="playlink" />bbbbb';
$t = preg_replace('#<input\ type="button"\ onclick="return play(\'(.*?)\',\ \'(.*?)\');"\ class="playlink"\ />#us', '{a:${1}:${2}}', $src);
echo $t;

?>

2 个答案:

答案 0 :(得分:0)

You can use the following regex:

<input.*?play\('(\w+?)',\s*?'(\w+?)'.*?\/>
Demo here.

Capture group 1 contains filename, group 2 contains the title.

答案 1 :(得分:0)

I got it to work like this:

$src = 'aaaaa<input type="button" onclick="return play(\'hellofile\', \'hellotitle\');" class="playlink" />bbbbb';
$rgx = '#<input type="button" onclick="return play\(' . "'(.*?)', '(.*?)'" . '\);" class="playlink" />#u';
$t = preg_replace($rgx, '{a:${1}:${2}}', $src);
echo "$t\n";