将sed字符串转换为PHP

时间:2008-10-21 22:00:44

标签: php regex

我有一个正在使用sed的正则表达式,但现在我还需要在PHP中使用它。我禁用系统调用。

$ cat uglynumber.txt:
Ticket number : 303905694, FOO:BAR:BAR: Some text
Case ID:123,456,789:Foobar - Some other text
303867970;[FOOBAR] Some text goes here
Case Ref: 303658850 - Some random text here - host.tld #78854w
$ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g"
303905694
123456789
303867970
303658850

那么,如何用PHP做同样的事情?

我发现了一个这样的例子,但我不能将那个正则表达式注入其中。

if (preg_match("/.../", $line, $matches)) {
  echo "Match was found";
  echo $matches[0];
}

3 个答案:

答案 0 :(得分:2)

尝试使用preg_replace()代替preg_match()grep sed preg_matchpreg_replace的对象是{{1}}。

答案 1 :(得分:2)

preg_replace()是您正在寻找的功能。您可以传递一组模式并替换参数

$pattern = array('/[, ]/','/.*\([0-9]\{9\}\).*/');
$replace = array('','$1');

foreach($lines as $line) {
   $newlines[] = preg_replace($pattern, $replace, $line);
}

答案 2 :(得分:2)

您的特定SED示例显然是2个正则表达式,1个正在替换逗号,1个技术上正在抓取9个数字的连续数字。

SED字符串的前半部分最适合preg_replace()函数。

//`sed s/regex/replace_value/flags`

preg_replace('/regex/flags', 'replace_value', $input);

您的SED字符串的后半部分是preg_match_all()

//`sed ...;s/regex/\1/flags`

$matches_array = array();
preg_match_all('/regex/flags', $input, &$matches_array);

因此,您的具体代码如下所示:

<?php
$input = file_get_contents('uglynumbers.txt');

$input = preg_replace('/[, ]/m','', $input);

$matches = array();
//No need for the .* or groupings, just match all occurrences of [0-9]{9}
if( preg_match_all('/[0-9]{9}/m', $input, $matches) )
{
    //...
    var_dump($matches);
}

看起来g是一个SED修饰符,意味着匹配所有行。 preg_match_all()应该已经处理了此修饰符,但根据PCRE modifiers上的手册,m似乎是一个合适的替换。