2

Is it possible to use strtolower in the substitution part of preg_replace?

This isn’t working:

preg_replace('/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org|tv|biz)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/i', '<a href="http://www.'.strtolower('$3').'" target="_blank">'.strtolower('$3').'</a>', $d);
Gumbo
  • 643,351
  • 109
  • 780
  • 844
Haroldo
  • 36,607
  • 46
  • 127
  • 169

2 Answers2

4

It is possible, yes. Have a look at the e modifier (Example #4):

preg_replace('/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org|tv|biz)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/ie', "'<a href=\"http://www.'.strtolower('$3').'\" target=\"_blank\">'.strtolower('$3').'</a>'", $d);

(Untested, the number of escaping backslashes may be wrong.)

jensgram
  • 31,109
  • 6
  • 81
  • 98
  • Thank you so much jensgram! Spot on except you only need to escape the " once (single backslash). nice one! – Haroldo Mar 10 '10 at 08:27
2

I favor using preg_replace_callback() over using the e(eval) modifier. I feel the code is cleaner, and has less room for error.

goat
  • 31,486
  • 7
  • 73
  • 96
  • +1 I'm tempted to agree with you. Only problem is that the syntax for anonymous function in PHP is not much cleaner, IMO :) – jensgram Mar 10 '10 at 09:12
  • Ya, create_function() is ugly. But in php 5.3+, anonyous functions are pretty nice. http://www.php.net/manual/en/functions.anonymous.php – goat Mar 10 '10 at 16:00