Bill
Bill

Reputation: 19268

PHP preg_replace and read the attribute within the string

The string I have used to looking for is below

<!-- PART -->

And it was easy, I just do

preg_replace('/<!-- PART -->/', $value);

But now I realise I need a new attribute to be added in the string (ID)

<!--  PART ID="zoneA" -->

So is it a way I can search for star with <!-- PART and end with --> and also if its possible to read the ID attribute value as well.

Upvotes: 0

Views: 291

Answers (2)

VIVEK-MDU
VIVEK-MDU

Reputation: 2559

try this

if( preg_match_all("/<!--[\w\s]+ID="(\w+)"\s?-->/",$text,$err_program)) {
print_r($err_program);
preg_replace("/<!--[\w\s]+ID="(\w+)"\s?-->/",$value,$text)
}   

Upvotes: 3

Expedito
Expedito

Reputation: 7795

if (preg_match_all('/<!--[\w\s]+ID="(\w+)"\s?-->/', $text, $matches)){
    echo $matches[1][0];//id
}

You can use the same pattern for preg_replace:

preg_replace('/<!--[\w\s]+ID="(\w+)"\s?-->/', $value, $text);

Do both together:

$pattern = '/<!--[\w\s]+ID="(\w+)"\s?-->/';
if (preg_match_all($pattern, $text, $matches)){
    $id = $matches[1][0];
    preg_replace($pattern, $value, $text);
}

Upvotes: 3

Related Questions