Digital Alchemist
Digital Alchemist

Reputation: 680

How to preg_replace spaces before and after the word

What i have:

$text = "
 randomword@staticwordrandomword@staticword  - False result 

 randomword@staticword    - True result 

 randomword@staticword randomword@staticword randomword@staticword  - True result 

 randomword@staticworandord@staticwordstauthello@staticwordord@staticword - False result

 randomword@ staticword  - False result

 randomword@staticword - True result 

 randomword@staticword    randomword@staticword      randomword@staticword  - True result"; 

$text = preg_replace('/(\s|^\s|\w*[a-zA-Z_]+\w*)@staticword($|\s)/', '\2<img src="image.png" border="0" alt="" /><a href="http://\1.site.com/"><b>\1</b></a>', $text); 

Result:

echo $text;

All TRUE results must be converted to a links and all FALSE not.

preg_replace must catch a "something@staticword" and convert it to a link , with a spaces before and after or no space at the end.

Example:

1 line - no links - plain text

2 line hello@staticword must be converted to a link.

Problem:

i cant get false results on 1st line and 4th line

Upvotes: 0

Views: 588

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use this pattern:

$pattern = '~(?<!@)\b([^\s@]++@staticword)\b(?!@)~';
$replacement = '<img src="image.png" alt="" /><a href="http://$1.site.com/">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

(and use css instead of border="0" and <b>)

Upvotes: 1

Related Questions