で区切られた特殊文字のリストがあり|
ます、としましょう$chars = "@ | ; | $ |";
そして、私は文字列を持っています、としましょう$stringToCut = 'I have @ list ; to Cut';
$stringToCut
のすべての文字から削除したい$chars
。
どうすればいいですか?
事前にThx
で区切られた特殊文字のリストがあり|
ます、としましょう$chars = "@ | ; | $ |";
そして、私は文字列を持っています、としましょう$stringToCut = 'I have @ list ; to Cut';
$stringToCut
のすべての文字から削除したい$chars
。
どうすればいいですか?
事前にThx
削除する文字のリストを配列に変換して使用します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);
正規表現を使用する代わりに、文字のリストを分解してください。
$chars = explode('|',str_replace(' ','','@ | ; | $ |'));//strip spaces, make array
echo str_replace($chars,'',$string);
str_replace
配列を最初または2番目の引数として受け入れます。ドキュメントも参照してください。
これにより、各文字を個別の対応する文字に置き換えるか、(ここで行ったように)すべてを何も置き換えない(別名、削除する)ことができます。
preg_replace()
削除するために使用
<?php
$chars = "@ | ; | $ |";
$stringToCut = 'I have @ list ; to Cut';
$pattern = array('/@/', '/|/', '/$/', '/;/');
$replacement = '';
echo preg_replace($pattern, $replacement, $stringToCut);
?>