我有一个html对象:
<a href="https://website/" class="td-post-category" value="News" >News</a>
我从键入$this->get_category()
得到的;用PHP。
我的问题是,是否有可能从PHP内部的HTML对象中获取值字段(新闻)。像$this->get_category().value
或$this->get_category()->value
之类的东西。就像我们可以在Javascript中一样。
或者,如果您知道如何从函数中“提取”变量。就像我在$selected_category_obj_name
中有一个名为function get_category()
的变量一样,当我编写$this->get_category()
时如何获得这个值,我怎样才能获得变量$selected_category_obj_name
?
我是PHP的新手,因此非常感谢一些指导。
您可以使用preg_match()
的正则表达式:
$html = '<a href="https://website/" class="td-post-category" value="News" >News</a>';
preg_match("/value=\"(.+)\"/i", $html, $matches);
var_dump($matches[1]); // News
该模式只是在value="
和"
之间寻找任何不止一次的东西,将结果返回到$matches
数组中。
或者DOMDocument
并遍历DOM以获取元素的属性:
$html = '<a href="https://website/" class="td-post-category" value="News" >News</a>';
$doc = new DOMDocument;
$doc->loadHTML($html);
var_dump($doc->getElementsByTagName("a")->item(0)->getAttribute("value")); // News