开发者

Multiple regular expression interfere

I u开发者_如何学Gose regex to create html tags in plain text. like this

loop

$SearchArray[] = "/\b(".preg_quote($user['name'], "/").")\b/i"; 
$ReplaceArray[] = '<a href="'.$user['url'].'">$1</a>';

-

$str = preg_replace($SearchArray, $ReplaceArray, $str);

I'm looking for a way to not match $user['name'] in a tag.


You could use preg_replace_callback()

for 5.3+:

$callback = function($match) using ($user) {
    return '<a href="'.$user['url'].'">'.$match[1].'</a>';
};
$regex = "/\b(".preg_quote($user['name'], "/").")\b/i"; 
$str = preg_replace_callback($regex, $callback, $string);

for 5.2+:

$method = 'return \'<a href="'.$user['url'].'">\'.$match[1].\'</a>\';';
$callback = create_function('$match', $method);
$regex = "/\b(".preg_quote($user['name'], "/").")\b/i"; 
$str = preg_replace_callback($regex, $callback, $string);


So the problem is that you're making several passes over the document, replacing a different user name in each pass, and you're afraid you'll unintentionally replace a name inside a tag that was created in a previous pass, right?

I would try to do all of the replacements in one pass, using preg_replace_callback as @ircmaxwell suggested, and one regex that can match any legal user name. In the callback function, you look up the matched string to see if it's a real user's name. If it is, return the generated link; if not, return the matched string for reinsertion.


It looks like you're trying to add a bunch of anchors to a document. Have you thought of using SimpleXML. This assumes that the anchor tags are part of a larger xhtml document.

//$xhtml_doc is some xhtml doc's path
$doc = simplexml_load_file($xhtml);
//NOTE: find the parent element for all these anchors (maybe with xpath)
//example: $parent = $doc->xpath('//div[@id=parent]');
foreach($user as $k => $v){
    $anchor = $doc->addChild('a', $v['name']);
    $anchor->addAttribute('href', $v['url']);
}
return $doc->asXML();

simpleXML helps me a lot in these situations. It'll be a lot faster than regex, even if this isn't exactly what you want to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜