0

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

3
  • Why box them inside square brackets and make a set? Commented May 13, 2013 at 15:26
  • Regexs dont work that way. You cant put a whole word in [..] Commented May 13, 2013 at 15:26
  • Similar answers gathered at once lol Commented May 13, 2013 at 15:31

5 Answers 5

3

You could just use str_replace

str_replace(array('$', 'Audio, CD, Audiobook, MP3 Audio, Unabridged'), '', $str);
Sign up to request clarification or add additional context in comments.

Comments

3

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);

1 Comment

So simple that i deleted my answer :3
2

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.

Comments

0

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)

1 Comment

I get that str_replace is preferable here, but I think the downvote is a bit much. This answer is correct and it is the only one that explains what was wrong with the OP's attempt.
0

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

1 Comment

He wants to replace the WHOLE string "Audio, CD, Audiobook, MP3 Audio, Unabridged"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.