将sed字符串转换为PHP

将sed字符串转换为PHP,php,regex,Php,Regex,我有一个与sed一起使用的regexp,但现在我还需要使它在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

我有一个与sed一起使用的regexp,但现在我还需要使它在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 uglynumber.txt: 票号:303905694,FOO:BAR:BAR:Some text 案例ID:123456789:Foobar-其他一些文本 303867970;[FOOBAR]这里有一些文字 案例参考:303658850-此处有一些随机文本-host.tld#78854w $cat uglynumbers.txt | sed“s/[,]//g;s/*\([0-9]\{9\}\)./\1/g” 303905694 123456789 303867970 303658850 那么,如何使用PHP实现同样的功能呢

我发现了一个这样的例子,但我不能将regexp注入其中

if (preg_match("/.../", $line, $matches)) { echo "Match was found"; echo $matches[0]; } if(preg_匹配(“/…/”,$line,$matches)){ echo“找到匹配项”; echo$匹配项[0]; } 尝试使用而不是
preg\u match()
grep
是要
sed
什么是
preg\u match
是要
preg\u replace
preg\u replace()
是您要寻找的函数。您可以传递一组模式并替换参数

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

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

您的特定SED示例显然是两个正则表达式,一个替换逗号,另一个从技术上讲是获取9位连续数字

SED字符串的前半部分最适合使用
preg\u replace()
函数

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

preg_replace('/regex/flags', 'replace_value', $input);
SED字符串的后半部分将是
preg\u match\u all()

因此,您的特定代码如下所示:

<?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);
}

我在每个测试中都有一个问题:警告:preg_replace()[function.preg replace]:未知修饰符“g”在…@boogie:我不太了解SED,所以请找到合适的修饰符there@boogie:看起来“g”在SED中表示全部匹配,在这种情况下,您不需要它,虽然您可能想为多重反应输入一个“m”,但请接受帮助您的答案。:)PHP中没有
g
修饰符<默认情况下,code>preg_replace()
将替换所有内容,并有一个可选参数来限制此操作。
//`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);
}