-4

I want to replace "hello" with "guys" except the image src and alt with PHP (case insensitive).

From

Hello hello HELLO <img src="hello.jpg" alt="hello" />

I want

Guys guys GUYS <img src="hello.jpg" alt="hello" />

or

guys guys guys <img src="hello.jpg" alt="hello" />

I tried with str_replace, str_ireplace, preg_replace but no result.

tomrozb
  • 25,773
  • 31
  • 101
  • 122
  • And your question is? – Marc B Apr 01 '13 at 22:00
  • 2
    writing some code would be one way to do it. or printing the text/html onto a piece of paper and then using whiteout to erase the text you don't want. We're not here to do your job for you. **YOU** write the code. if it doesn't work, then you post that code and someone may try to help you. – Marc B Apr 01 '13 at 22:03
  • are there going to be multiple `` in the string? – Ejaz Apr 01 '13 at 22:04
  • hello, this is the complete code `$words = array(); $links = array(); $result = mysql_query("SELECT `keyword`, `link` FROM `articles` where `link`!='".$act."' ") or die(mysql_error()); $i = 0; while($row = mysql_fetch_array( $result )) { if (!empty($row['keyword'])) { $words[$i] = $row['keyword']; $links[$i] = ''.$row['keyword'].''; $i++; } } $text = str_ireplace($words, $links, $text);` – user2233781 Apr 01 '13 at 22:09
  • but the problem is that it replaces also the alt tags and src from my text – user2233781 Apr 01 '13 at 22:09
  • the "complete" question! http://stackoverflow.com/questions/15753137/php-replace-words-to-links-except-images – user2233781 Apr 02 '13 at 00:06

2 Answers2

2

If you want to match both hello following both alt=" and src=" you could use a "negative lookbehind" for both of those. Something like:

$string = 'Hello hello HELLO <img src="hello.jpg" alt="hello" />';
preg_replace('/(?<!(src|alt)=")hello/i', 'guys', $string);
  • almoust perfect... but my keyword has multiple words, it does not work! Here is the complete "problem" http://stackoverflow.com/questions/15753137/php-replace-words-to-links-except-images – user2233781 Apr 02 '13 at 00:10
1

You want to use a "Negative Lookahead." Here's my proof of concept code.

<?php
$string = "Hello, hello, HELLO hello.jpg";
print preg_replace("/hello(?!.jpg)/i", 'Guys', $string);

Prints

Guys, Guys, Guys hello.jpg
jcbwlkr
  • 7,789
  • 2
  • 22
  • 28