简体   繁体   English

还原字符串并替换字符-RegP with Php

[英]Reversion Strings and replace a character - RegEx with Php

I have a doubt again on RegEx in Php. 我再次对PHP中的RegEx感到怀疑。

Assume that I have a line like this 假设我有这样一条线

716/52  ; 250/491.1; 356/398; 382/144

I want the output to be 我希望输出是

  1. Replace all semi-colon with comma. 用逗号替换所有分号。 I think I can do this using 我想我可以使用

     $myline= str_replace(";", ",", $myline); 
  2. Interchange the numbers and replace '/' with a comma. 交换数字并用逗号替换“ /”。 That is, 716/52 will become 52,716. 也就是说,716/52将变为52,716。 This is where I get stuck. 这就是我卡住的地方。

So, the output should be 因此,输出应为

52,716 , 491.1,250, 398,356, 144,382

I know that using sed, I can achieve it as 我知道使用sed可以实现

1,$s/^classcode:[\t ]\+\([0-9]\+\)\/\([0-9]\+\)/classcode: \2\,\1/

But, how do I do it using preg_match in php? 但是,如何在php中使用preg_match?

$str = '716/52  ; 250/491.1; 356/398; 382/144';

$str = str_replace(';', ',', $str);

$res = preg_replace_callback('~[\d.]+/[\d.]+~', 'reverse', $str);

function reverse($matches)
{
    $parts = explode('/', $matches[0]);
    return $parts[1] . ',' . $parts[0];
}

var_dump($res);

And working sample: http://ideone.com/BeS9j 和工作示例: http : //ideone.com/BeS9j

UPD : PHP 5.3 version with anonymous functions UPD :具有匿名功能的PHP 5.3版本

$str = '716/52  ; 250/491.1; 356/398; 382/144';

$str = str_replace(';', ',', $str);

$res = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
    $parts = explode('/', $matches[0]);
    return $parts[1] . ',' . $parts[0];
}, $str);

var_dump($res);

As an alternative to Regexen you could try this: 作为Regexen的替代方法,您可以尝试以下方法:

echo join(', ', array_map(
     function ($s) { return join(',', array_reverse(explode('/', trim($s)))); },
     explode(';', $string)));
$str = '716/52  ; 250/491.1; 356/398; 382/144';
$str = preg_replace('(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)', '$2,$1', $str);
$str = str_replace(';', ',', $str);

Uses two capture groups, replacing them in reverse order. 使用两个捕获组,以相反的顺序替换它们。 See it here . 在这里看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM