Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 287
  • Last Modified:

preg_replace problem

I'm getting an error:
 
Warning: preg_replace() [function.preg-replace]: Unknown modifier '(' in C:\Documents and Settings\Brian\Desktop\test-cake\app\webroot\test.php on line 11

Line 11 is the preg_replace() function call.

I'm trying to use back references to replace the url and re-write links so that I can force a target on links.

I'm very very very new to regular expressions, my experience level is about 2.5 hrs... ;)



Thanks.
Brian

$html = '<a href="http://www.google.com">Link</a><a target="_none" href="http://www.google.com"></a>< a style="" href="www.yahoo.com" t arget="_blank"     >as   dajsdj< /A >< A href="" target="_self">askjkajlsd<a><a href="test">sdsdfsfsdfs</a>';
 
/* remove newlines so we can use regex */
$html = str_replace("\n","",$html);
 
/* rewrite links to open in a new window and remove tags */
$html = preg_replace('<\s*(?i:a).*(?i:href=)"([^"]*)".*>(.*)<\s*/\s*(?i:a)\s*>', 
                     '<a href="$1" target="_blank">$2</a>',
                     $html);
 
echo $html;

Open in new window

0
BrianGEFF719
Asked:
BrianGEFF719
  • 2
1 Solution
 
ozoCommented:
preg_replace('{<\s*(?i:a).*(?i:href=)"([^"]*)".*>(.*)<\s*/\s*(?i:a)\s*>}',
                     '<a href="$1" target="_blank">$2</a>'
0
 
BrianGEFF719Author Commented:
Hi Ozo,
That does resolve the error; however, I'm only getting back the last link...


Ideas?
0
 
BrianGEFF719Author Commented:
The issue was resolved by using a lazy quantifier (?) eg .*?
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now