简体   繁体   English

PHP:preg_match不起作用

[英]PHP: preg_match not working

I have the following code: 我有以下代码:

$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value){
if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/',$value)){
echo 'code';
echo '<br />';
}else{
echo 'Not code';
echo '<br />';
}
}

I want to check if each of the lines starts with 4 spaces and if it does i want to echo as 'Code' and if it doesn't i want to echo as 'Not code'. 我想检查每行是否以4个空格开头,是否要以“代码”作为回显,如果不是,我要以“非代码”作为回显。 But i am getting the output as 'Not code' though the 2nd , 3rd and 4th lines start with four spaces. 但是,尽管第二,第三和第四行以四个空格开头,但我将输出显示为“非代码”。 I cannot figure out what I have done wrong. 我无法弄清楚我做错了什么。 Please help me. 请帮我。

nl2br doesn't generate <br /> unless you tell it to. 除非您告知nl2br ,否则不会生成<br /> Your explode logic is wrong. 您的explode逻辑是错误的。

Instead, try this: 相反,请尝试以下操作:

$data = "Normal text.......";
foreach(explode("\n",$data) as $line) {
    // your existing foreach content code here
}

got it working added a trim() to get rid of the newline in front of the string 得到它的工作添加了trim()以摆脱字符串前面的换行符

nl2br replace \\n with <br />\\n (or <br />\\r\\n ), so when spliting on <br /> the \\n is left as the first char nl2br将\\n替换为<br />\\n (或<br />\\r\\n ),因此在<br />上拆分时, \\n保留为第一个字符

<?php
        $data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";

        $data = nl2br($data);

        $data= explode('<br />', $data );

        foreach($data as $value)
        {
                if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/', trim($value)))
                {
                        echo 'code';
                }
                else
                {
                        echo 'Not code';
                }
                echo '<br />';
        }
?>

You could also use "startsWith" as defined here... 您还可以使用此处定义的“ startsWith” ...

https://stackoverflow.com/a/834355/2180189 https://stackoverflow.com/a/834355/2180189

...instead of the regexp match. ...而不是regexp匹配。 That is, if the spaces are always at the beginning 也就是说,如果空格始终在开头

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

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