简体   繁体   中英

Problems with Regular expressions in PHP

(I want to let my users tag other users with their names, problem: when someone edits his post again, he gets the link in his tinymce editor. when he saves his edits, the script will destroy the old link...)

I replace all words in a big string with words included in an array.

$users = {'this', 'car'}
$text = hello, this is <a title="this" href="">a test this</a>
$search = '!\b('.implode('|', $users).')\b!i';
$replace =  '<a target="_blank" alt="$1" href="/user/$1">$1</a>';
$text = preg_replace($search, $replace, $text);

as you can see above, I try to replace 'this' and 'car' in $text with

<a target="_blank" alt="$1" href="/user/$1">$1</a>

the problem is, that my script also replaces 'this', when it's in my link:

<a title="this" href="">this</a>

im not completely sure, but I think, you know what I mean. so my script destroys my links...

I don't need to detect, if the word is in a html element, because it should be able to replace words in other tags like h1 or p ...

I need something like a pattern, which only matches, when the word looks like: " this " " this, " ",this " " this: "... (no problem, if i have to set these manually...)

another great solution: a string, where I can set the html tags which are not allowed.

$tags = 'a,e,article';

Greets

This should do it

<.*?this.*?>(*SKIP)(*FAIL)|\b(this)\b

Demo: https://regex101.com/r/fX0pT1/1

More on this regex approach, http://www.rexegg.com/regex-best-trick.html .

PHP Usage:

$users = array('this', 'car');
$text = 'hello, this is <a title="this" href="">a test this</a>';
$terms = '(' . implode('|', $users) . ')';
$search = '!<.*?'.$terms.'.*?>(*SKIP)(*FAIL)|\b(' . $terms . ')\b!i';
echo $search;
$replace =  '<a target="_blank" alt="$2" href="/user/$2">$2</a>';
echo preg_replace($search, $replace, $text);

Output:

hello, <a target="_blank" alt="" href="/user/this">this</a> is <a title="this" href="">a test <a target="_blank" alt="" href="/user/this">this</a></a>

PHP Demo: https://eval.in/415964

...or if you only want it for links, https://regex101.com/r/fX0pT1/2 , <a.*?this.*?>(*SKIP)(*FAIL)|\\b(this)\\b .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM