regex - PHP: What is the pattern to find numbers-dashed sub-strings and replace after modification?
Get the solution ↓↓↓I have strings with numbers-dashes sub-strings. I want to find these sub-strings and replace them after some modifications.
For example, the string is like:
- This is the string number 123-45-6789-0 which contains 12-34567.
Now I want to find sub-strings of numbers-dashes (123-45-6789-0 and 12-34567) and replace them with the modified sub-strings. For example the final string would be like this:
- This is the modified string number 0-6789-45-123 which contains 34567-12.
I have already triedpreg_match_all(string $pattern, string $subject, array &$matches)
with:
$pattern = '/-*\d+-*/';
but it gives me an array of numbers each one with a dash, like this:
$matches = [123-, 45-, 6789-, 0, 12-, 34567]
whereas, I want an array of two sub-strings, like this:
$matches = [0 => 123-45-6789-0, 1 => 12-34567]
in order to do modifications and replacements (usingstr_replace()
), separately.
Which pattern and methods should I use for these purpose?
Thanks in advance.
Answer
Solution:
You may use{{-code-6}code{-code-6}1}
regex with a preg_replace_callback` function:
$str = 'This is the string number 123{-code-6}45{-code-6}6789{-code-6}0 which contains 12{-code-6}34567.';
echo preg_replace_callback('~{{-code-6}code{-code-6}1}~', function({-code-7}) {
return implode('{-code-6}', array_reverse({-code-9}('{-code-6}', {-code-7}[0]))); }
,$str);
// => This is the string number 0{-code-6}6789{-code-6}45{-code-6}123 which contains 34567{-code-6}12.
See PHP demo and the regex demo.
The{{-code-6}code{-code-6}1}
pattern matches
{{-code-6}code{-code-6}4}
{-code-6} 1+ digits(?:{-code-6}{{-code-6}code{-code-6}4})+
{-code-6} 1 or more occurrences of{-code-6}
and 1+ digits sequences.
{-code-7}
is a match array,{-code-7}[0]
holds the match value. With{-code-9}
, the string is split with{-code-6}
, then the array is reversed, and then joined back withimplode
.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function illuminate\encryption\openssl_cipher_iv_length()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.