如何在PHP中比较字符串并忽略斜杠和反斜杠

时间:2015-09-05 20:24:12

标签: php regex

我想比较两个字符串并忽略斜杠和反斜杠。

例如,我的预期结果:

Regex found: tools/dbgprint/dbgprint.c
Trimmed from $regex->key(): base/applications\cmdutils\dbgprint\dbgprint.c
Output echo: Different!!

Regex found: base/applications/cmdutils/help/help.c
Trimmed from $regex->key(): base/applications\cmdutils\help\help.c
Output echo: This same

Regex found: dll\app\mplay32\mplay32.
Trimmed from $regex->key(): dll\app\mplay32\mplay32.c
This same

这是我的代码(输出不等于上面提到的,但我想你明白这一点):

$ROSDir = 'E:/ReactOS/';    
(...)    
$re = "/^\\s*\\*\\sFILE:\\s*\\K(\\S*)/m"; 

(...)
    if (!$regex->isDot())
    {
        $fileContent = file_get_contents($regex->key());

        preg_match_all($re, $fileContent, $matches);

        if (isset($matches[0][0]))
        {
            echo 'File: <b>'. $regex->key() .'</b><br>';

            echo 'Re found: '. $matches[0][0] .'<br>';

            $subject = $regex->key();
            $trimmed = str_replace($ROSDir, '', $subject);
            echo 'Trimmed: '. $trimmed .'<br>';

            if ($matches[0][0] !== $trimmed)
            {
                echo 'Different!!<br>';
            }
        }
}
    (...)

1 个答案:

答案 0 :(得分:0)

$slash = str_replace('\\', '/', $trimmed);

            $backslash = str_replace('/', '\\', $trimmed);

            if ($matches[0][0] !== $slash && $matches[0][0] !== $backslash)
            {
                echo 'File: <b>'. $regex->key() .'</b><br>';

                echo 'Re found: '. $matches[0][0] .'<br>';

                echo 'Trimmed: '. $trimmed .'<br>';

                echo 'Different!!<br>';
                $diffHeader++;

                echo '<hr>';
            }