0

I want to replace a number of characters in a string, so I have looked at preg_replace:

preg_replace('/xyz/', '', $val);

Yet the above only replaces instances of xyz and not individual characters. Here is an example of what I want to happen:

preg_replace('/xyz/', '', 'xaybzc'); //abc
preg_replace('/xyz/', '', 'xyzabc'); //abc
preg_replace('/xyz/', '', 'abzxyc'); //abc
0

2 Answers 2

2

A pattern is the literal string. For optional you can use a character class or optional values.

preg_replace('/x|y|z/', '', $val);

or

preg_replace('/[xyz]/', '', $val);

what character class you also can use ranges:

preg_replace('/[x-z]/', '', $val);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, what if I wanted to also remove the characters []| from the string?
You would escape those and put them into either method you'd like. e.g. preg_replace('/[\[\]|xyz]/', '', $val); or preg_replace('/\[|\]|\||x|y|z/', '', $val); (I find the character class considerably easier to read/use)
Use the escape character in front of them. Like [a\[\]b] or a|\||b
1

An alternative to preg_replace is str_replace with an array:

str_replace(['x', 'y', 'z'], '', 'xaybzc'); // abc
str_replace(['x', 'y', 'z'], '', 'xyzabc'); // abc
str_replace(['x', 'y', 'z'], '', 'abzxyc'); // abc

If you want to remove [, ] and | as well, simply add them to the array:

$replaceArray = ['x', 'y', 'z', '[', ']', '|'];
str_replace($replaceArray, '', 'x[a]b|cyz'); // 'abc'

Comments

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.