I have this code.
<?php
$USClass = "3/312";
$USClass = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $USClass);
echo $USClass;
?>
It prints 312,3 which is what I wanted.
However, if I give an input like D12/336 then it does not work. I want it to print 336,D12
How can I do it? and What is wrong with my current code which is not handling this Alphanumeric? Is it because I used \d ?
EDIT:
I want it to handle inputs like t开发者_StackOverflow社区his as well
148/DIG.111
then the output should be DIG.111,148
Yes \d
does only contain digits.
You can try \w
instead this is alphanumeric, but additionally it includes also _
To be Unicode you can go for
~[\pL\d.]+/[\pL\d.]+~u
\pL
is a Unicode code point with the property "Letter"
The u
at the end turn on the UTF-8 mode that is needed to use this feature
See http://www.php.net/manual/en/regexp.reference.unicode.php
Other solution
I think you ar e doing this a bit complicated. It would be simplier if you would make use of capturing groups.
Try this:
$in = "148/DIG.111";
preg_match_all('~([\w.]+)/([\w.]+)~', $in, $matches);
echo $matches[2][0] . ',' . $matches[1][0];
Explanation:
([\w.]+)/([\w.]+)
^^^^^^^^ ^^^^^^^^
Group 1 Group 2
Because of the brackets the matched substring is stored in the array $matches
.
See here for more details on preg_match_all
With a simple preg_replace:
$USClass = "148/DIG.111";
$USClass = preg_replace('#(.+?)/(.+)#', "$2,$1", $USClass);
echo $USClass;
output:
DIG.111,148
精彩评论