简体   繁体   English

如何使用preg_match查找html标签?

[英]How to use preg_match to find html tags?

I'm trying to make this code work by seeing if the returned data contains any html tags with php but it doesn't seem to work.. 我正在尝试通过查看返回的数据是否包含任何带有html的html标记来使此代码正常工作,但是它似乎不起作用。

function returnRegflow() 
{
    $data = "<html><body>";
    return $data;


    if(preg_match('html', $data))
    {
        echo 'error';

    } else if(strpos($data, 'regflow') !== false){
        echo $data;
    }
}

echo returnRegflow();

Some issues: 一些问题:

  • Your function is exiting too early by the return before the if , so it never got to checking for tags; 您的函数在if之前通过return退出为时过早,因此它永远不必检查标签;
  • preg_match expects the first argument to be regular expression, so it needs a delimiter at the start and the end (like / ); preg_match期望第一个参数是正则表达式,因此它需要在开始和结束处使用定界符(例如/ );
  • A function that tests the variables it has set itself is a bit useless, you should pass it the string that should be tested: that way it can be used for different strings; 一个测试它自己设置的变量的函数是没有用的,您应该将要测试的字符串传递给它:这样可以将它用于不同的字符串;
  • using echo to output the result is not how functions work. 使用echo输出结果不是函数的工作方式。 Instead return the result, as a string or maybe as a boolean; 而是以字符串或布尔值的形式返回结果;

You seem to be looking for something like this: 您似乎正在寻找这样的东西:

function returnRegflow($data) {
    if (preg_match('/<\w/', $data)) {
        return 'contains tags';
    }
    if (strpos($data, 'regflow') !== false){
        return $data;
    }
    return 'does not contain "regflow"';
}

echo returnRegflow("<html><body>"); 

The check for tags is quite rudimentary: it checks whether the text contains anything that looks like <a , where a can be any letter. 对标签的检查非常简单:它检查文本是否包含看起来像<a任何内容,其中a可以是任何字母。

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

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