We help IT Professionals succeed at work.

preg replace with newline

XK8ER
XK8ER asked
on
Medium Priority
367 Views
Last Modified: 2012-05-12
hello,
I have a little code that its working perfectly fine but I would like to add a little feature so it remove cows.net at the bottom
its not removing cows.net because it doesn't have any text at the end
<?php
$str = 'text here google.com text here
text here http://cows.net/search/query?123 text here
text here cats.net text here
text here bird.org, text here
text here cows.net
text here';

$result = preg_replace('/(?:cows\.com|cats\.net|bird\.org)[, .]/i', '', $str);

echo $result;
?>

Open in new window

Comment
Watch Question

Terry WoodsWeb Developer, specialising in WordPress
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
$result = preg_replace('/(?:cows\.net|cats\.net|bird\.org)([, .]|$)/im', ' ', $str);

Works for me... note you had cows\.com rather than cows\.net in your pattern.

Author

Commented:
im talking about the cows.net on line 6
Terry WoodsWeb Developer, specialising in WordPress
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
Yes, my solution assumes that.

Author

Commented:
this is what im using

text here google.com text here
text here http://cows.net/search/query?123 text here
text here cats.net text here
text here bird.org, text here
text here cows.net
text here

after your code this is what I get

text here google.com text here
text here http://cows.net/search/query?123 text here
text here text here
text here  text here
text here cows.net
text here

it should remove the last cows.net
Terry WoodsWeb Developer, specialising in WordPress
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
My solution worked for me:
<?php
$str = 'text here google.com text here
text here http://cows.net/search/query?123 text here
text here cats.net text here
text here bird.org, text here
text here cows.net
text here';

$result = preg_replace('/(?:cows\.net|cats\.net|bird\.org)([, .]|$)/im', ' ', $str);

echo $result."\n";
?>

Output:
text here google.com text here
text here http://cows.net/search/query?123 text here
text here  text here
text here   text here
text here
text here

Open in new window

Author

Commented:
im not getting the same results.. maybe because I am using PHP v5.3.8?
Web Developer, specialising in WordPress
CERTIFIED EXPERT
Most Valuable Expert 2011
Commented:
An alternative might be this - in both this pattern and the previous one, I'm assuming cows.net is at the end of the line.

$result = preg_replace('/(?:cows\.net|cats\.net|bird\.org)([, .]|(?=\r?\n))/i', '', $str);