preg_replace pattern needed. replace double chars with single char
I'm not that familiar with patterns so that's why I'm asking it here instead of going through a trail and error proces. I know it is not the best way to learn but I have more important things to code.
basically I want to replace any double occurrences of a given char with a single char. This is for cleaning input strings before validation. for example
$string='hello///stack/overflow/ // //!';
$string2='hello((stack(overflow(((( (!';
$clean= preg_replace($pattern, '/',$string );开发者_运维知识库
$clean2= preg_replace($pattern, '(',$string2 );
echo $clean;
echo $clean2;
the above code should echo hello/stack/overflow/! and hello(stack(overflow(!, with the correct pattern of course... :-)
any help appreciated!
peace
edit: actually I would be more then happy with a pattern that does the job without dealing with the whitespaces. I can strip them like so
preg_replace('/\s+/xms', '', trim($value))
and then deal with the double chars...
Are you sure you want to replace only double occurences? From your example seems you want to replace 2 or more same characters.
If you need to do it only for some specific chars use
$value = preg_replace('/\\{2,}/', '\', trim(preg_replace('/\s+/', '', $value));
First, your regex pattern is incorrect to start with, the use of the / is designed to identify the start and end of a pattern. For example $pattern='/-/';
will look for the - to replace
The full example of a regex would be as follows:
$string='this/is/my/pattern';
$pattern='///';
$replacement=' ';
preg_replace($pattern, $replacement, $string);
To answer your question, nobody could explain it as well as in this article so check that out.
The PHP documentation on preg_replace is good so I would recommend going through that also.
精彩评论