Eric Wang
Eric Wang

Reputation: 436

PHP preg_match captures not working as expected

<?php
$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
<span id="userStatusText" class="text-overflow ng-binding userstatus-editable" title="_epic Can I have Coffee" ng-class="{'userstatus-editable':profileHeaderLayout.mayUpdateStatus}" ng-bind="profileHeaderLayout.statusText|statusfilter" ng-click="revealStatusForm()">"_epic Can I have Coffee"</span>
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

preg_match("!<span.+id=\"userStatusText\".+>(.*)<\/span>!", $html, $element);

if (!$element) {
  return;
}
echo $element[0];

I apologize for the atrocious variable, but I am trying to fetch _epic Can I have Coffee from the string.

I have been trying to fetch the string inside the parenthesis which were called captures on the PHP documentation.

I want to be able to capture the text inside (.*) which is not working.

When executing the preg_match, I would still get only the span element <span ...>...</span> (substitute ... for the content in the $html variable).

I have looked on several threads and documentation and couldn't find anything that would answer my issue.

Here is what it looks like when I execute it enter image description here

I'm not trying to get the element but getting the text inside the Right Here

Upvotes: 0

Views: 93

Answers (1)

Nick
Nick

Reputation: 147206

DOMDocument and DOMXPath are the more appropriate way to parse HTML in PHP:

$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
<span id="userStatusText" class="text-overflow ng-binding userstatus-editable" title="_epic Can I have Coffee" ng-class="{'userstatus-editable':profileHeaderLayout.mayUpdateStatus}" ng-bind="profileHeaderLayout.statusText|statusfilter" ng-click="revealStatusForm()">"_epic Can I have Coffee"</span>
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//span[@id="userStatusText"]') as $span) {
    echo $span->getAttribute('title');
}

Output:

_epic Can I have Coffee

Demo on 3v4l.org

Upvotes: 1

Related Questions