Hi all,
Can you help me how to separate letters from numbers?
So, if i have string like site123point, I would like to be site-123-point.
Thank you in advance!!!
Hi all,
Can you help me how to separate letters from numbers?
So, if i have string like site123point, I would like to be site-123-point.
Thank you in advance!!!
$str = '123site123point123';
$str = preg_replace('/^(\\d+)/', '$1-', $str);
$str = preg_replace('/(\\d+)$/', '-$1', $str);
$str = preg_replace('/([^\\d]+)(\\d+)([^\\d]+)/', '$1-$2-$3', $str);
var_dump($str); // string(22) "123-site-123-point-123"
First replace numbers at the start of the string with the numbers followed by a -
Then replace all numbers at the end of the string with a - and then the numbers
Lastly, replace numbers within the string by -(numbers)-
PS. If you have to process a lot of strings, you’ll probably want to write a simple “parser” using strpos() and [url=http://nl3.php.net/manual/en/function.substr-replace.php]substr_replace(), since preg_replace is not the fastest function out there.
<?php
preg_match_all(
'~([a-z]+)|([0-9]+)~i',
'sitepoint12345demo',
$matches
);
echo implode(
'-',
$matches[0]
);
#sitepoint-12345-demo
?>
And another preg_* function!
$subject = 'sitepoint12345demo';
$parts = preg_split('/(\\d+)/', $subject, NULL, PREG_SPLIT_DELIM_CAPTURE);
echo implode('-', $parts);
// sitepoint-12345-demo
I like ScallioXTXs code because it would be the easiest to take into consideration Unicode characters with if that’s something that’s needed down the road.
Might be better to use trim() to get rid of the extra hyphens though.
$str = '4site123point';
$_str = preg_replace('#([^\\d])?(\\d+)([^\\d])?#', '$1-$2-$3', $str);
echo trim($_str, '-');
Yes and no. Yes the code is more neat and somewhat faster. No that also removes hyphens that were originally in the string before “rewriting” it.
Consider applying the function to “-site123point-”, you’d end up with “site-123-point”
If you’re sure strings never start or end with a hyphen trim()'ing is fine of course
Good point.