Tim
Tim

Reputation: 403

Looking to preg replace a domain from a string

What regular expression would one use to remove a domain from a string? I tried several combinations and the closet I come up with works expect removes everything afterwards when a match as been found more than once.

$string = 'The quick brown fox <img src="http://domain.com/images/fox.jpg"> jumps over the lazy dog.';
preg_replace('/http:\/\/(.*)domain.com/', '', $string);`

Looking detect and remove the following combinations www.domain.com, domain.com and subs.domain.com within an img and href src.

Upvotes: 0

Views: 3286

Answers (2)

Michael Wright
Michael Wright

Reputation: 591

You need to escape fullstops ...

/http:\/\/[a-z\.]+domain\.com/

Upvotes: 1

qbert220
qbert220

Reputation: 11556

Your .* is greedy. It will consume as many characters as it can to satisfy the match. Put a ? after it to make it non-greedy like this:

preg_replace('/http:\/\/(.*?)domain\.com/', '', $string);

Upvotes: 6

Related Questions