0

我正在尝试@从文本块中删除标志。问题是在某些情况下(在一行的开头,@标志需要保留。

我已经通过使用 RegEx 模式成功了.\@,但是当@符号确实被删除时,它也会删除它前面的字符。

目标:删除所有@符号,除非@符号是该行中的第一个字符。

<?php

function cleanFile($text)
{
    $pattern = '/.\@/';
    $replacement = '%40';
    $val =  preg_replace($pattern, $replacement, $text);
    $text = $val;
    return $text;
};

$text  = ' Test: test@test.com'."\n";
$text .= '@Test: Leave the leading at sign alone'."\n";
$text .= '@Test: test@test.com'."\n";
$valResult = cleanFile($text);
echo $valResult;

?>

输出:

Test: tes%40test.com
@Test: Leave the leading at sign alone
@Test: tes%40test.com
4

3 回答 3

2

在这种简单的情况下不需要正则表达式。

function clean($source) {
    $prefix = '';
    $offset = 0;
    if( $source[0] == '@' ) {
         $prefix = '@';
         $offset = 1;
    }

    return $prefix . str_replace('@', '', substr( $source, $offset ));
}

和测试用例

$test = array( '@foo@bar', 'foo@bar' );
foreach( $test as $src ) {
    echo $src . ' => ' . clean($src) . "\n";
}

会给:

@foo@bar => @foobar
foo@bar => foobar
于 2013-08-20T15:48:44.917 回答
2

可以使用正则表达式使用否定的lookbehind 执行此操作:(/(?<!^)@/m一个@符号前面没有行首(或者如果您跳过修饰符,则为字符串的开头m))。

正则表达式 101 演示

在代码中:

<?php
    $string = "Test: test@test.com\n@Test: Leave the leading at sign alone\n@Test: test@test.com;";
    $string = preg_replace("/(?<!^)@/m", "%40", $string);
    var_dump($string);
?>

输出以下内容:

string(84) "Test: test%40test.com
@Test: Leave the leading at sign alone
@Test: test%40test.com;"

键盘演示

于 2013-08-20T15:52:13.703 回答
0

语法 [^] 表示否定匹配(如不匹配),但我认为以下内容行不通

$pattern = '/[^]^@/';
于 2013-08-20T15:50:18.843 回答