preg 替换标签外的文本

preg replace text outside of a tags

我对正则表达式一无所知。但我需要解决这个问题。 我想替换标签外的所有文本。(如果有任何标签)

这是我的代码:

$entry = preg_replace("'\(find: (.*)\)'Ui","(find: <a href=\"/search/\1/\"><b>\1</b></a>)",$entry);

它应该替换 html 标签之外的 (find: foo)。

我试过了,但没用。因为我不明白正则表达式:(

preg_replace("'([^<]+?>)\(find: (.*)\)([^<]+?>)'Ui","(find: <a href=\"/find/\1/\"><b>\1</b></a>)",$entry);

提前谢谢你。 :)

编辑: 这是我的例子:

// some users do this. and it brokes the text.

$entry = "blablabla (find: (user: bora)) blablabla ";

function entry($entry) {
    $entry = preg_replace("'\(find: (.*)\)'Ui","<a href=\"/find/\1/\"><b>\1</b></a>",$entry);
    $entry = preg_replace("'\(user: (.*)\)'Ui","(user: <a href=\"/user/\1/\"><b>\1</b></a>)",$entry);
    $entry = stripslashes($entry);
    return $entry;
}

以下是防止您描述的问题的方法:

function linkit($match) {
    $item = urlencode($match[1]); // "user" or "find", made safe for URL
    $href = urlencode($match[2]); // part after ":", made safe for URL
    $content = htmlentities($match[2]); // part after ":" made safe for HTML
    return "<a href='/$item/$href/'><b>$content</b></a>";
}

function entry($entry) {
    // Use one replace operation for both "find" or "user":
    // For each match the function linkit is called. 
    // These 3 characters may not occur before closing parentheses:
    //    ( < >
    $entry = preg_replace_callback("'\((find|user): ([^(<>]*?)\)'ui", 
                                   'linkit', $entry);
    return $entry;
}

$entry = "blablabla (find: (user: bora)) blablabla ";
echo entry($entry);

输出:

blablabla (find: <a href='/user/bora/'><b>bora</b></a>) blablabla 

如您所见,"(find: ...)" 没有被替换,因为在第一个右括号之前还有另一个左括号。即使您在此结果上再次调用 entry(),它也不会改变,因为在 "(查找:...."