Question

I'm trying to replace first occurrence of the string "Harvey" with the link <a href='/harvey'>Harvey</a>

I'm using "/(?<!(src|alt|href)=\")".$internal_links_row['key_phrase']."/i" as the search pattern, it only skips matching when there is exact match in the alt/src pattern.

For Eg: It matches alt="Harvey". But it does not match alt="James Stewart in Harvey",

I need to skip every occurrence within the double quotes and I can not use strip_tags

Please help me guys, Thanks

Was it helpful?

Solution

Try using:

Harvey(?![^<>]*>)

Which makes sure there's no closing angled bracket ahead indicating it's inside an HTML tag.

If that doesn't work nicely, maybe a positive lookahead instead:

Harvey(?=[^<>]*(?:<|\Z))

Which makes sure there's the opening angled bracket of a tag ahead, or the end of the string.

Which translates to:

"/".$internal_links_row['key_phrase']."(?![^<>]*>)/i"
"/".$internal_links_row['key_phrase']."(?=[^<>]*(?:<|\Z))/i"

respectively

EDIT: As per comment:

"~".$internal_links_row['key_phrase']."(?=[^<>]*(?:<(?!/a)|\Z))~i"
 ^                                                  ^^^^^^     ^

I changed the delimiters and added a negative lookahead.

OTHER TIPS

why not use str_replace()

$ans = str_replace('href="/harvey", 'href="/some_string"', $subject);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top