简体   繁体   中英

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%>.

Ps: private should be public

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

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

You should use str_replace instead.

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM