PHP中的哪个函数验证字符串是否为有效的html? [英] Which function in php validate if the string is valid html?

查看:113
本文介绍了PHP中的哪个函数验证字符串是否为有效的html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php中的哪个函数验证字符串是否为html?
我的目标是从用户处获取输入,并检查输入html是否是字符串。



非html字符串示例:

  sdkjshdk< div> jd< / h3> ivdfadfsdf或sdkjshdkivdfadfsdf 

html字符串示例:

 < div> sdfsdfsdf< label> dghdhdgh< / label> fdsgfgdfgfd< / DIV> 

谢谢

解决方案您可能需要检查字符串是否正常形成。



我会使用这样的函数

 函数检查($ string){
$ start = strpos($ string,'<');
$ end = strrpos($ string,'>',$ start);

$ len = strlen($ string);

if($ end!== false){
$ string = substr($ string,$ start);
} else {
$ string = substr($ string,$ start,$ len- $ start);
}
libxml_use_internal_errors(true);
libxml_clear_errors();
$ xml = simplexml_load_string($ string);
return count(libxml_get_errors())== 0;
}

只是一个警告:html允许不平衡的字符串,如下所示。它不是一个xml有效的块,而是一个合法的html块。

 < ul>< li>您好< li>我是另一个li< / li>< / ul> 

免责声明我修改了代码即可。为了检测字符串中格式良好的html。

最后一个
也许你应该使用 strip_tags 来控制用户输入(正如我在评论中看到的那样)


Which function in php validate if the string is html? My target to take input from user and check if input html and not just string.

Example for not html string:

sdkjshdk<div>jd</h3>ivdfadfsdf or sdkjshdkivdfadfsdf

Example for html string:

<div>sdfsdfsdf<label>dghdhdgh</label> fdsgfgdfgfd</div>

Thanks

解决方案

Maybe you need to check if the string is well formed.

I would use a function like this

function check($string) {
  $start =strpos($string, '<');
  $end  =strrpos($string, '>',$start);

  $len=strlen($string);

  if ($end !== false) {
    $string = substr($string, $start);
  } else {
    $string = substr($string, $start, $len-$start);
  }
  libxml_use_internal_errors(true);
  libxml_clear_errors();
  $xml = simplexml_load_string($string);
  return count(libxml_get_errors())==0;
}

Just a warning: html permits unbalanced string like the following one. It is not an xml valid chunk but it is a legal html chunk

<ul><li>Hi<li> I'm another li</li></ul>

Disclaimer I've modified the code (without testing it). in order to detect well formed html inside the string.

A last though Maybe you should use strip_tags to control user input (As I've seen in your comments)

这篇关于PHP中的哪个函数验证字符串是否为有效的html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆