preg_replace question
DiggBlinkRedditDeliciousTechnorati
question by Bejaan | Moderate
Hi All,
I've the following statement:
$LinkName = preg_replace('/\s/s', '-', $LinkTitle);
Now as far as I understand in regular expressions '\s' stands for whitespace, but I can't figure out what is meant by '/\s/s'
So can someone explain to me please?
Thanks in advance
Post reply
Subscriptions
Re: preg_replace questionreply by Srirangan Replace white space with - in the variable $linktitle and assign this to $linkname and the /s means single line mode.
The two front slashes contain the actual pattern, which is just \s
The extra s aftewards is a modifier that let's a dot metacharacter in the patter match all characters, including new lines, so this is not even really needed in your statement (as far as I know).
More info on the modifiers:
http://us3.php.net/manual/en/reference.pcre.pattern.modifiers.php
I think you could accomplish the same thing with str_replace, and it would probably be more efficient:
$Linkname = str_replace("\s", "-", $LinkTitle);
Or, this would probably work just the same:
$Linkname = str_replace(" ", "-", $LinkTitle);
Post reply
Subscriptions
Re: preg_replace questionanswer by mastercomputers Make sure to read Srirangan's answer, as I'm only adding onto his reply.
Regular Expression patterns are delimited by the /{regex}/{modifiers} forwards slashes, you can also use @{regex}@{modifiers} e.g. Inside your regular expression pattern would go, outside would be the modifiers.
The \s is for any whitespace character.
Although 's' modifier (represented as /s) use to mean single-line mode, it's long since changed that meaning due to the possibility of combining /s single-line mode and /m multi-line mode which worked strangely enough.
The 's' modifier is the PCRE_DOTALL modifier.
To explain this, it's used with the dot character (.) which means any character including non-printable, except newlines.
The 's' modifier allows the any character dot to capture newlines as well. It makes no sense using it, unless you use the any character dot and need to detect newline characters.
e.g. Let /./ match newlines or treat \n as an ordinary character.
For more information on Pattern Modifiers and Pattern Syntax, look at http://php.net/manual/en/reference.pcre.pattern.modifiers.php and http://php.net/manual/en/reference.pcre.pattern.syntax.php.
What I assume this code is for is producing a string that is browser friendly by removing the spaces used for rewriting links. Otherwise presenting a link with spaces would result in many %20 (HTML encoded space character) in your addressbar.
Other things I suggest looking into is PHP Interpolation, though aimed specifically at Srirangan. Double quotes versus Single Quotes, there's quite a performance difference to be gained using the correct means.
Post reply
Subscriptions
Got a PHP Question?
Just Sign Up and ask the top PHP experts!
|