3

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 this as well

148/DIG.111

then the output should be DIG.111,148

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Great! This code works! <?php $USClass = "148/DIG.111"; $USClass = preg_replace_callback('~[\w.]+/[\w.]+~', function ($matches) { $parts = explode('/', $matches[0]); return $parts[1] . ',' . $parts[0]; }, $USClass); echo $USClass; ?>
@Bhavani Kannan I updated my answer with a Unicode solution. I think the \w will only cover ascii letters.
@Bhavani Kannan I updated my answer again with a maybe better solution.
2

With a simple preg_replace:

$USClass = "148/DIG.111";
$USClass = preg_replace('#(.+?)/(.+)#', "$2,$1", $USClass);
echo $USClass;

output:

DIG.111,148

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.