Hi I want to delete this character: |
with php preg replace.
My code do n开发者_运维知识库ot work
$rstr = '|||is';
$Grab->text = preg_replace($rstr,'',$Grab->text);
echo $Grab->text;
If you really waht to use a regular expression, you need to escape the |
character, which as a special meaning :
$Grab->text = preg_replace('#\|#is', '', $Grab->text);
This is supposing you only want to replace one |
, and not three in a row -- in which case you'd use :
$Grab->text = preg_replace('#\|{3}#is', '', $Grab->text);
Also note that I used #
as delimiters -- it's easier to write/read the regex when delimiters are not characters that are present inside the regex : less escaping to do.
But, as @Pekka noted in his comment to your question, why not just use str_replace()
?
$Grab->text = str_replace('|', '', $Grab->text);
Or, if you only want the replacement to be made when there are three |
:
$Grab->text = str_replace('|||', '', $Grab->text);
After all, in a simple case such as this one, there is no need for regular expressions.
|
is a regex meta-character, and you also use it as the delimiter (and that's 2 problems).
You should escape the |
sign, and use another delimiter (you also don't need the i
and s
flags):
$rstr = '~\|~';
Your regex was interpeted as ~~|is
, and had the following error message:
Warning: preg_replace(): Unknown modifier '|' in /home/o3oYmU/prog.php on line 3
|
has special meaning in a regex, it is used for alternation (ie a|b|c
means a or b or c) so you have to escape it :
$Grab->text = preg_replace("/\|\|\|is/",'',$Grab->text);
or double escape if you assing a string $rstr = '\\|\\|\\|is';
精彩评论