jackhao
jackhao

Reputation: 3817

Replace certain words with link, but exclude word that already in a link

I wanted to use regex/string replace function in PHP so I can replace certain keyword with links: Say there is a string: `

"Hello guys I want to ask a programming questions."

The output should be

"Hello guys I want to ask a <a href="https://www.stackoverflow.com">programming</a> questions."

It sounds like something can be easily done with regex/string functions, however, I found out that if there is already a link in the string, like:

"Hello guys I want to ask a <a href="https://www.stackoverflow.com">programming related</a> questions."

The normal regex/string replace function will make it:

"Hello guys I want to ask a <a href="https://www.stackoverflow.com"><a href="https://www.stackoverflow.com">programming</a> related</a> questions."

Note that there is a "" inside another tag. What should I do so if the string, say "programming" is already in a link, it won't convert it? Is it possible?

Thanks!

Upvotes: 0

Views: 217

Answers (3)

aggressionexp
aggressionexp

Reputation: 780

try to use negative assertion

Lookbehind assertions start with (?<= for positive assertions and (?< ! for negative assertions for negative assertions

Lookahead assertions start with (?= for positive assertions and (?! for negative assertions

examples:

http://www.ibm.com/developerworks/library/os-php-regex2/

http://sabirul-mostofa.blogspot.com/2011/05/php-regex-lookaround-assertion.html

PHP Regex negative look behind assertion, preg_replace_callback

Upvotes: 1

Dhivya
Dhivya

Reputation: 699

In the string replace function pass your word to be replaced with space before and after the word like this.. This may solve your problem I think

$str= "Hello guys I want to ask a programming questions. Hello guys I want to ask a <a href='https://www.stackoverflow.com'>programming</a> questions.";
$str=str_replace(" programming ",'<a href="https://www.stackoverflow.com">programming</a>',$str);
var_dump($str);

Output

"Hello guys I want to ask a <a href='https://www.stackoverflow.com'>programming</a> questions. Hello guys I want to ask a <a href='https://www.stackoverflow.com'>programming</a> questions."

Upvotes: 0

This would work

<?php
$str='Hello guys I want to ask a <a href="https://www.stackoverflow.com">programming-related</a> questions.';

$str=strip_tags($str);
$str=str_replace("programming",'<a href="https://www.stackoverflow.com">programming</a>',$str);

var_dump($str);

OUTPUT:

string(101) "Hello guys I want to ask a <a href="https://www.stackoverflow.com">programming</a>-related questions."

Upvotes: 0

Related Questions