I have a list of special chars separated by |
, lets say $chars = "@ | ; | $ |";
And I have an string, let's say $stringToCut = 'I have @ list ; to Cut';
I want to remove from $stringToCut
all chars in $chars
.
How would I do that ?
Thx in advance
I would convert your list of characters to remove to an array and use str_replace
:
$chars_array = explode($chars);
// you might need to trim the values as I see spaces in your example
$result = str_replace($chars_array, '', $stringToCut);
Use preg_replace()
to remove
<?php
$chars = "@ | ; | $ |";
$stringToCut = 'I have @ list ; to Cut';
$pattern = array('/@/', '/|/', '/$/', '/;/');
$replacement = '';
echo preg_replace($pattern, $replacement, $stringToCut);
?>
Ok, instead of using regex, just explode the list of chars:
$chars = explode('|',str_replace(' ','','@ | ; | $ |'));//strip spaces, make array
echo str_replace($chars,'',$string);
str_replace
accepts an array as first and/or second argument, too see the docs.
This enables you to replace each char by a distinct counterpart, or (as I did here) replace them all with nothing (aka remove them).