What is a regex that will allow me to get the text inside this tag?

时间:2016-10-15 17:00:56

标签: php regex

Using a regex, how can I delete/replace everything and keep only the score inside the tag?

The data-v is variable.

<a href="/football/italy/1-division-phase-a/fixtures/7-days/#" data-y="f1" data-v="this-is-variable">2 - 0</a>

2 个答案:

答案 0 :(得分:0)

You can use regex in preg_match() to select target part of string.

preg_match("/>([^<]+)</", $str, $matches);
echo $matches[1];

See result in demo


Also because your string is html, you can parse it using DOMDocument class and get text of element.

$dom = DOMDocument::loadHTML($str);
$text = $dom->getElementsByTagName("a")->item(0)->nodeValue;

See result in demo

答案 1 :(得分:0)

It really depends on the context but if you can rely on the 'data-y="f1"' as an anchor to the page, something like this should work:

if (preg_match('{<a href="[^"]+"[^>]*\sdata-y="f1"[^>]*>([^<]+)</a>}', $data, $match) { ... use $match[1] ... }

I did not test it but I will explain it so you can fine-tune:

{          open regexp (instead of /)
<a href="  literal match
[^"]+      anything up to the next " (so you match the href url)
"          literal
[^>]*      any other content of the <a ...> tag which you don't care about
\s         make sure there is a space
data-y="f1"  literal match (your "anchor")
[^>]*      any other content you don't care about
>          literal (close <a>)
([^<]+)    payload
</a>       literal
}          close regexp