Home > Back-end >  Remove characters from a string using preg replace?
Remove characters from a string using preg replace?

Time:08-25

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

CodePudding user response:

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

CodePudding user response:

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'
  •  Tags:  
  • php
  • Related