Predrag Drekalović Predrag Drekalović - 3 years ago 192
PHP Question

How to return the numbers back to the string as reversed

I'm working on the practice and I got an example of how the program works

Entry: "Dlasdf234dkl sdfkl8886adaf15adfjk7 asdflkj376661a s445s198"

Output: "Dlasdf432dkl sdfkl6888adaf51adfjk7 asdflkj166673a s544s891"


I managed to get all the numbers regardless of where they are, and I did that by explode and implode. I have numbers as strings and because I did it in a loop, I am stuck and can't get numbers back in original string.

When I try to put them back in string I get this mess:

Array
(
[0] => Array
(
[a] => Dlasdf432dkl sdfkl432adaf432adfjk432 asdflkj432a s432s432
[sub] => Пошаљи
)

[1] => Array
(
[a] => Dlasdf6888dkl sdfkl6888adaf6888adfjk6888 asdflkj6888a s6888s6888
[sub] => Пошаљи
)

[2] => Array
(
[a] => Dlasdf51dkl sdfkl51adaf51adfjk51 asdflkj51a s51s51
[sub] => Пошаљи
)

[3] => Array
(
[a] => Dlasdf7dkl sdfkl7adaf7adfjk7 asdflkj7a s7s7
[sub] => Пошаљи
)

[4] => Array
(
[a] => Dlasdf166673dkl sdfkl166673adaf166673adfjk166673 asdflkj166673a s166673s166673
[sub] => Пошаљи
)

[5] => Array
(
[a] => Dlasdf544dkl sdfkl544adaf544adfjk544 asdflkj544a s544s544
[sub] => Пошаљи
)

[6] => Array
(
[a] => Dlasdf891dkl sdfkl891adaf891adfjk891 asdflkj891a s891s891
[sub] => Пошаљи
)
)

Answer Source

You'll want to use regex to parse out the numbers and replace them:

<?php

$str = 'Dlasdf234dkl sdfkl8886adaf15adfjk7 asdflkj376661a s445s198';


echo preg_replace_callback('~([0-9]{2,})~', function($matches) { return strrev($matches[1]); }, $str);
// Dlasdf432dkl sdfkl6888adaf51adfjk7 asdflkj166673a s544s891

?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download