user2351471
user2351471

Reputation: 71

PHP preg_replace all occurrences for tags

I have this:

$tagName = "id";
$value = "ID12345";
$text = "<%id%> some text <%id%> something";
$a = new A();
echo $a->replaceAllTags($tagName, $value, $text);

and I want to create this:

"ID12345 some text ID12345 something"

Tried this and didn't work:

private function replaceAllTags($tagName, $value, $text)
{
    $pattern = "/<%" . $tagName . "%>/";
    while (preg_match($pattern, $text)) {
        $text = preg_replace($pattern, $value, $text);
    }
    return $text;
}

This didn't work too:

private function replaceAllTags($tagName, $value, $text)
{
    $pattern = "/<%(" . $tagName . ")%>/";
    $text = preg_replace_callback($pattern, 
        function($m) {
           return $value;
    }, $text);
    return $text;
}

EDITED: Problem was that I wrote a PHPUnit test and had <%id> instead of <%id%>.

P.s.: private should be public

Upvotes: 0

Views: 177

Answers (5)

Dexa
Dexa

Reputation: 1651

You should use str_replace instead.

private function replaceAllTags($tagName, $value, $text)
{
    $pattern = "<%" . $tagName . "%>";
    $text = str_replace($pattern, $value, $text);
    return $text;
}

Upvotes: 0

Alexander Borisov
Alexander Borisov

Reputation: 401

  1. Your method A::replaceAllTags declared as a private instead of public. Details here
  2. If you want use regexp - try this snippet.

    class A { 
         public function replaceAllTags($tagName, $value, $text) {
             $pattern = "/<%(" . $tagName . ")%>/";
             $text = preg_replace($pattern, $value, $text);
             return $text;    
         }    
     }
    

I advise you to use simple str_replace. Like this:

public function replaceAllTags($tagName, $value, $text) {
    $pattern = "<%" . $tagName . "%>";
    $text = str_replace($pattern, $value, $text);
    return $text;
}

Upvotes: 1

Daniel Fanica
Daniel Fanica

Reputation: 450

There is nothing wrong with any of the functions! Just keep in mind that your functions are private functions and can only be accessed withing that class!

Upvotes: 0

Youness
Youness

Reputation: 1495

this worked fine for me try it :

<?php
     function replaceAllTags($tagName, $value, $text)
    {
        $pattern = "/(<%)(" . $tagName . ")(%>)/";
        while (preg_match($pattern, $text)) {
            $text = preg_replace($pattern, $value, $text);
        }
        return $text;
    }
    $tagName = "id";
    $value = "ID12345";
    $text = "<%id%> some text <%id%> something";

    echo replaceAllTags($tagName, $value, $text);
?>

the result was : ID12345 some text ID12345 something

Upvotes: 0

Lanai Grunt
Lanai Grunt

Reputation: 36

Besides the fact that a regex is not really needed for that, it seems to me the problem is with the "private" visibility. A method which you want to access from the outside needs the "public" visibility.

http://php.net/manual/en/language.oop5.visibility.php

Upvotes: 1

Related Questions