Bill
Bill

Reputation: 19268

Regular Expression with getting the value within the String

I want to do a string replace within HTML content.

<!-- REPLACE_STRING_5 -->

In order to do that, i need to get the number of out the string (ID) I just want to check am I doing it correctly and efficiently?

<?php
$subject = "<!-- REPLACE_STRING_21 -->";
$pattern = '/^<!-- REPLACE_STRING_[0-9\.\-]+ -->/';

if(preg_match($pattern, $subject))
{
    $pos = strpos($subject, '-->');
    //20 is the number where the number postion start
    $pos = $pos - 20;
    echo substr($subject, 20, $pos);
}
else
{
    echo 'not match';
}

Upvotes: 1

Views: 41

Answers (1)

brandonscript
brandonscript

Reputation: 72895

If you're trying to actually replace the number in REPLACE_STRING_21 you could use lookarounds to do this:

(?<=<!-- REPLACE_STRING_)[-0-9.]+(?= -->)

enter image description here

Working example: http://regex101.com/r/tK5cI1

Since you want to capture the number out, you could use parentheses () to deploy capture groups, like so:

<!-- REPLACE_STRING_([-0-9.]+) -->

Working example: http://regex101.com/r/tV4tI3

You then need to retrieve the capture group 1 like so:

$subject = "<!-- REPLACE_STRING_21 -->";    
preg_match("/<!-- REPLACE_STRING_([-0-9.]+) -->/", $subject, $matches);
print_r($matches);
if (isset($matches[1]))
    echo $matches[1];

$matches will contain an array of matches, which in this case, $matches[1] is the one you're looking for.

Upvotes: 2

Related Questions