【问题标题】:php replace some strings between tags or charsphp替换标签或字符之间的一些字符串
【发布时间】:2019-06-21 17:53:23
【问题描述】:

我需要替换字符串中的一些文本。我认为一个例子可以更好地解释:

[myFile.json]

{ "Dear":"newString1", "an example string":"newString2" }

[example.php]

$myString = "@Dear@ name, this is @an example string@.";

function gimmeNewVal($myVal){
    $obj = json_decode(file_get_contents('myFile.json'));
    return $obj->$myVal;
}

echo gimmeNewVal("Dear"); // This print "newString1"

所以,我需要找到“@”符号之间的任何字符串,并且对于找到的每个字符串,我需要使用 gimmeNewVal() 函数进行替换。

我已经尝试过使用 preg_* 函数,但我不太会使用正则表达式...

感谢您的帮助

【问题讨论】:

  • 你的预期输出是什么?
  • 你在哪里使用$myString
  • 如果你真的需要为此使用正则表达式:regex101.com

标签: php json regex replace


【解决方案1】:

你也可以使用T-Regx tool:

pattern('@([^@])@')->replace($input)->all()->by()->map([
    '@Dear@' => "newString1", 
    '@an example string@' => 'newString2'
]);

pattern('@([^@])@')->replace($input)->all()->group(1)->by()->map([
    'Dear' => "newString1", 
    'an example string' => 'newString2'
]);

您还可以使用方法by()->map()by()->mapIfExists()by()->mapDefault()。无论你需要什么:)

【讨论】:

    【解决方案2】:

    您可以使用preg_match_all 来匹配@somestring@ 类型的所有字符串,使用正则表达式@([^@]+)@,然后遍历for 循环以替换原始字符串中的每个此类找到的字符串,以替换为来自的实际值你的函数 gimmeNewVal 从你给定的 json 返回值。

    这是相同的 PHP 代码,

    $myString = "@Dear@ name, this is @an example string@.";
    
    function gimmeNewVal($myVal){ // I've replaced your function from this to make it practically runnable so you can revert this function as posted in your post
        $obj = json_decode('{ "Dear":"newString1", "an example string":"newString2" }');
        return $obj->$myVal;
    }
    
    preg_match_all('/@([^@]+)@/', $myString, $matches);
    for ($i = 0; $i < count($matches[1]); $i++) {
        echo $matches[1][$i].' --> '.gimmeNewVal($matches[1][$i])."\n";
        $myString = preg_replace('/'.$matches[0][$i].'/',gimmeNewVal($matches[1][$i]), $myString);
    
    }
    echo "\nTransformed myString: ".$myString;
    

    打印转换后的字符串,

    Dear --> newString1
    an example string --> newString2
    
    Transformed myString: newString1 name, this is newString2.
    

    如果这是你想要的,请告诉我。

    【讨论】:

      【解决方案3】:

      你可以使用 preg_replace_callback 函数

      $myString = "@Dear@ name, this is @an example string@.";
      
      $obj = json_decode(file_get_contents('myFile.json'));
      
      echo preg_replace_callback('/@([^@]+)@/', 
              function ($x) use($obj) { return isset($obj->{$x[1]}) ? $obj->{$x[1]} : ''; }, 
              $myString);
      

      demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-26
        • 2011-02-20
        • 2019-10-31
        • 2015-04-29
        • 1970-01-01
        • 1970-01-01
        • 2016-05-12
        相关资源
        最近更新 更多