Reputation: 393
can you explain this regular expression.
$price = "...555.55";
$price = preg_replace('/^./', '', $price);
output:
$price = ..555.55;
Upvotes: 0
Views: 59
Reputation: 213223
The regex '/^./'
matches any character at the beginning of the string.
dot(.)
matches any character except the newline
character, andcaret(^)
is used to match at the beginning.So, your preg_replace
is replacing any character at the beginning with an empty string.
So, ...555.55
becomes ..555.55
after replacing the first .
.
If you just want to replace all the dots(.)
from the beginning, then you have to escape the .
in your regex. Since simply using .
will match any character. Also, you need to use some quantifier - *
or +
to replace more dots(.)
.
So, your regex would be:
preg_replace('/^[.]+/', '', $price);
or:
preg_replace('/^\.+/', '', $price);
Upvotes: 3
Reputation: 336128
/^./
matches the first character after the start of the string.
/
and /
delimit the regex.^
matches the position at the start of the string, .
matches any character unless it's a linebreak). That match will be replaced by the empty string (''
).
If you want to replace the first three characters:
$price = preg_replace('/^.{3}/', '', $price);
If you want to replace all dots at the start of the string, you need to escape them and apply a quantifier (+
meaning "one or more"):
$price = preg_replace('/^\.+/', '', $price);
If you want to replace all non-digits at the start of the string (which might make more sense):
$price = preg_replace('/^\D+/', '', $price);
Upvotes: 1