preg替换标签之外的文本

时间:2016-01-29 22:01:10

标签: php html regex preg-replace

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

这是我的代码:

$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;
}

1 个答案:

答案 0 :(得分:0)

以下是如何防止您描述的问题:

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(),它也不会改变,因为在的右括号之前有一个小于号的符号(找到:... 。“