0

I have a regular expression which is it returns anything inside the html tag with id="test"

ex:

<span id="test">Hello World</span>

 <.*?id="pStyle".*?>(.*?)</.*?>

it returns Hello World

what if a tag is empty it should return too like

<span id="test"></span>

it should return a default value if a tag is empty. I'm currently new on regex is there any regular expression to derrive this empty tags?

Darline
  • 195
  • 3
  • 13

2 Answers2

0

Maybe after any symbols <.*?id="pStyle".*?>(.*?)</.*?> You should add more than one symbol

<(.*)id="pStyle"(.*)>(.*)<\/ (.*)>

For me it worked fine

falsetru
  • 357,413
  • 63
  • 732
  • 636
Farhad
  • 742
  • 6
  • 22
0

I assume that you use preg_match function. It will always return a string when there is a match. If you want to return null if the tag is empty I think you should add an if statement, e.g.

$string = '<span id="test">Hello World</span>';
$matches = array();
if (preg_match('%<.*?id="pStyle".*?>(.*?)</.*?>%', $string, $matches) {
    if (empty($matches[1])) {
        return null;
    }
    return $matches[1];
}

Also I'd suggest not using this structure: .*?. If I would write this RegEx, I would do it that way:

<[^>]*id="pStyle"[^>]*>([^<]*)</[^>]*>

[^>]* means: Zero or more characters other than >.

matewka
  • 9,912
  • 2
  • 32
  • 43
  • i come up with this it wont do anything ` $value = 'A'; $match = array(); if(preg_match('%<[^>]*id="test2"[^>]*>([^<]*)[^>]*>%', $html, $match)) { $html = str_replace($match[1],$value,$html); }` – Darline Nov 16 '13 at 08:36
  • @Darline is your goal to replace the text inside the tag with the `A` string? – matewka Nov 16 '13 at 10:50