user1989379
user1989379

Reputation: 175

preg_replace when using string

I have the following preg_replace function

preg_replace('/[\$,Audio, CD, Audiobook, MP3 Audio, Unabridged]/','',$audibleinnertextpieces)

this is my regular expression to replace either the $ or the WHOLE string

Audio, CD, Audiobook, MP3 Audio, Unabridged

for some reason it is removing the U in all my strings, I just want to replace if the WHOLE string is found to match Audio, CD, Audiobook, MP3 Audio, Unabridged

Upvotes: 0

Views: 96

Answers (5)

rcbevans
rcbevans

Reputation: 8882

You can use the regex

$regex = "/\$|Audio, CD, Audiobook, MP3 Audio, Unabridged/"

which will search for either the $ symbol or the entire string. then just use

$result = preg_replace($regex, '' ,$audibleinnertextpieces)

Which will strip any of the search terms out

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208425

In regular expressions square brackets create a character class which will one single character from any character between the brackets. So [abc] would match either 'a', 'b', or 'c'.

If you want to match $ or Audio, CD, Audiobook, MP3 Audio, Unabridged then you want alternation, which is accomplished by separating the pieces with a |:

preg_replace('/\$|Audio, CD, Audiobook, MP3 Audio, Unabridged/','',$audibleinnertextpieces)

Upvotes: 0

SomeShinyObject
SomeShinyObject

Reputation: 7801

Why not just use str_replace instead:

str_replace(array('$','Audio, CD, Audiobook, MP3 Audio, Unabridged'),'',$string);

If you know the EXACT string that you want replaced, a regular expression is overkill.

Upvotes: 2

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17752

Don't use regex for these kind of searches. Why not use plain str_replace?

$str = str_replace(array('$', 'Audio, CD, Audiobook, MP3 Audio, Unabridged'), '', $source_string);

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191729

You could just use str_replace

str_replace(array('$', 'Audio, CD, Audiobook, MP3 Audio, Unabridged'), '', $str);

Upvotes: 3

Related Questions