如想要用sprintf動態替換%s,如何做到?
像這類regular expression字串動態處理的方式,該如何google,
因為都只查到regular expression的用法
不考慮replace的方式
$regex = '/.*?<a name="%s">(.*?)<a name="%s">/is';
<?php
$url1 = '/blog';
$url2 = '/about';
$template = '/.*?<a href="%s">(.*?)<\/a><a href="%s">/is';
$pattern = sprintf($template, preg_quote($url1,'/'), preg_quote($url2,'/'));
echo 'pattern = ' . htmlspecialchars($pattern) . '<br/>';
$subject = '<a href="/">HOME</a><a href="/blog">BLOG</a><a href="/about">ABOUT</a>';
echo 'subject = ' . htmlspecialchars($subject) . '<br/>';
preg_match($pattern, $subject, $matches);
echo 'matches[1] = ' . htmlspecialchars($matches[1]) . '<br/>';
?>