Php 多重正则表达式干涉

Php 多重正则表达式干涉,php,regex,preg-replace,Php,Regex,Preg Replace,我使用正则表达式以纯文本形式创建html标记。像这样 循环 $SearchArray[] = "/\b(".preg_quote($user['name'], "/").")\b/i"; $ReplaceArray[] = '<a href="'.$user['url'].'">$1</a>'; 我正在寻找一种不匹配标记中的$user['name']的方法。您可以使用 对于5.3+: $callback = function($match) using ($user)

我使用正则表达式以纯文本形式创建html标记。像这样

循环

$SearchArray[] = "/\b(".preg_quote($user['name'], "/").")\b/i"; 
$ReplaceArray[] = '<a href="'.$user['url'].'">$1</a>';
我正在寻找一种不匹配标记中的
$user['name']
的方法。

您可以使用

对于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);
$callback=函数($match)使用($user){
返回“”;
};
$regex=“/\b”(.preg_quote($user['name'],“/”)\b/i”;
$str=preg_replace_callback($regex,$callback,$string);
对于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);
$method='return\';';
$callback=create_函数($match',$method);
$regex=“/\b”(.preg_quote($user['name'],“/”)\b/i”;
$str=preg_replace_callback($regex,$callback,$string);

所以问题在于,您对文档进行了多次传递,在每次传递中替换不同的用户名,并且您担心会无意中替换上一次传递中创建的标记中的名称,对吗


我会尝试一次完成所有替换,使用@ircmaxwell建议的
preg_replace_callback
,以及一个可以匹配任何合法用户名的正则表达式。在回调函数中,查找匹配的字符串以查看它是否是真实的用户名。如果是,则返回生成的链接;如果没有,请返回匹配的字符串以重新插入。

看起来您正在尝试向文档添加一组锚定。您想过使用SimpleXML吗。这假设锚定标记是更大的xhtml文档的一部分

//$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在这些情况下对我帮助很大。它将比正则表达式快得多,即使这不是您想要做的。

我从未在php中使用过这样的回调。我正在使用PHP5.2。。我可以把这个代码循环200次吗?你可以。。。性能可能是一个问题(使用
str_ireplace()
可能会更好,但您将无法保留名称的大小写)…我仍然无法在PHP5.2中获得一个工作循环。错误是“语法错误,意外”,对用户名有什么限制?哪些字符是合法的?有最小或最大长度要求吗?对第一个字符有进一步的限制吗?例如,名称必须以字母开头吗?我们需要这些信息来创建regex.the regex”/\b(“.preg_quote($user['name'],“/”)\b/i“对我有用速度并不重要。我还想用另外一个词来匹配自己的正则表达式。好的,但我要做的是创建一个正则表达式,它将匹配任何有效的用户名,并且(尽可能)不匹配任何其他名称。只需匹配该用户名的正则表达式,而不是其他任何内容。然后循环正则表达式。
//$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();