preg_replace仅括号之间的数字

时间:2012-07-05 08:29:43

标签: preg-replace

我需要在括号之间替换数字。例如

(1) should be (<a href="1">1</a>) --> I could do this
(1,2,5,8) should be (<a href="1">1</a>,<a href="2">2</a>,<a href="5">5</a>,<a href="8">8</a>)
(2-5, 13) should be (<a href="2">2</a>-<a href="5">5</a>,<a href="13">13</a>)

我无法完成最后两次转换。

1 个答案:

答案 0 :(得分:1)

<?php
//Config
$pattern='/\((\d|\s|,|\d+-\d+)+\)/';
$replacement='<a href="$0">$0</a>';
$subject='foo 1 bar (baz) (1) whatever (2,3,4) something (7-9,11) more';


//Callback
$callbackbody="return preg_replace('/\d+/','$replacement',\$matches[0]);";
$callback=create_function('$matches',$callbackbody);


//main
echo preg_replace_callback($pattern, $callback, $subject);
?>