0

in my PHP script I have a variable like the following:

$names = '<a href="%URL$%" rel="tag">Name Surname</a>, <a href="%URL$%" rel="tag">Name Surname</a>, <a href="%URL$%" rel="tag">Name Surname</a>';

Is it possible to filter $names in order to have this result?

$names = '<a href="%URL$%" rel="tag">N. Surname</a>, <a href="%URL$%" rel="tag">N. Surname</a>, <a href="%URL$%" rel="tag">N. Surname</a>';
Pennywise83
  • 1,784
  • 5
  • 31
  • 44
  • 1
    Yes, using [DOM manipulation](http://stackoverflow.com/questions/27222/dom-manipulation-in-php). A regex is [not going to help](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – CodeCaster Jun 13 '12 at 11:30
  • What do you mean by filter? You just want to replace "Name" with "N.". Are there other requirements? – stema Jun 13 '12 at 11:56
  • Yes, I obviously have different names and I'd like to take only the first character followed by a dot. ex: John Smith, Mark Twain => J. Smith, M. Twain – Pennywise83 Jun 13 '12 at 12:08

2 Answers2

0

You could use preg_replace_callback:

$names = preg_replace_callback(
             '/(<a[^>]*>)(\w+)( \w+</a>)',
             function($matches) {
                 return $matches[1] . substr($matches[2], 0, 1) . "." . $matches[3];
             },
             $names
         );
ctn
  • 2,887
  • 13
  • 23
-1

Really short answer: Use a HTML parser (like http://simplehtmldom.sourceforge.net/)

Regexes and HTML only work when you are sure you are only pulling apart a really predictable string of code.

Powertieke
  • 2,368
  • 1
  • 14
  • 21