簡體   English   中英

PHP preg_replace所有出現的標簽

[英]PHP preg_replace all occurrences for tags

我有這個:

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

我想創建這個:

"ID12345 some text ID12345 something"

嘗試了一下,但是沒有用:

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

這也不起作用:

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

編輯: 問題是我寫了一個PHPUnit測試,並具有<%id>而不是<%id%>。

附:私人應該公開

除了實際上並不需要正則表達式外,在我看來,問題還在於“私有”可見性。 您要從外部訪問的方法需要“公共”可見性。

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

  1. 您的方法A :: replaceAllTags聲明為私有而不是公共。 詳情在這里
  2. 如果要使用regexp,請嘗試以下代碼段。

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

我建議您使用簡單的str_replace 像這樣:

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

您應該改為使用str_replace

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

這對我來說很好用,嘗試一下:

<?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);
?>

結果是: ID12345一些文本ID12345一些

任何功能都沒有錯! 請記住,您的函數是私有函數,只能通過該類進行訪問!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM