如何交换字符串中的数字?

时间:2019-04-17 16:56:17

标签: php

能帮我找到正确的函数来交换字符串中的数字吗?数字以“:”分隔。

例如

"2:0" to "0:2"
"101:50" to "50:101"

谢谢。

2 个答案:

答案 0 :(得分:1)

有很多方法可以做到,您可以在这里尝试任何一种方法。

<?php
//using regex
$re = '/(\d+):(\d+)/i';
$str = '50:101';
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
echo "The string $str after exchange is ".$result;

echo PHP_EOL;
// concatenating parts after explode
$parts = explode(':',$str);
echo "The string $str after exchange is $parts[1]:$parts[0]";

echo PHP_EOL;
//using explode, array_reverse and implode
$str = '50:101';
$result = implode(':', array_reverse(explode(':',$str)));
echo "The string $str after exchange is ".$result;
?>    

演示: https://3v4l.org/OkY18

答案 1 :(得分:0)

只需explode()字符串,然后对其进行重新格式化。

$str = '100:200';
$bits = explode(':',$str);
echo $bits[1] . ':' . $bits[0];

结果

200:100