0

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.

2 Answers 2

3
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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Wow legend it works and it did read the ID attribute, but preg_replace failed tho
can i do a whole string replace after i get the ID value? => <!-- PART ID="zoneA" --> would love to give u a tick still need 1 min :)
@bluebill1049 - I just updated with code to do both together.
actually one more small question, what if the string appear twice this pattern, can you read id one by one? String => test<!-- PART ID="zoneA" --> test <!-- PART ID="zoneB" -->
@bluebill1049 - You can use print_r($matches) to see the structure of the array. In this case your ids should be $matches[1][0], $matches[1][1], $matches[1][2], etc. The number 1 in the first key indicates that you want what is in the parenthesis of the pattern as opposed to 0 which matches the whole expression.
3

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)
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.