douxihui8270 2019-01-28 17:01
浏览 81
已采纳

php替换标签或字符之间的一些字符串

I need to replace some text in a string. I think an example can explain better:

[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"

So, what I need is to find any strings between the '@' symbol and for each string found I need to replace using the gimmeNewVal() function.

I already tried with preg_* functions but I'm not very able with regex...

Thanks for your help

  • 写回答

3条回答 默认 最新

  • dongwo5589 2019-01-28 18:54
    关注

    You can use preg_match_all to match all strings of type @somestring@ using regex @([^@]+)@ and then iterate over a for loop to do the replacement of each such found string in the original string to replace with the actual value from your function gimmeNewVal which returns the value from your given json.

    Here is the PHP code for same,

    $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])."
    ";
        $myString = preg_replace('/'.$matches[0][$i].'/',gimmeNewVal($matches[1][$i]), $myString);
    
    }
    echo "
    Transformed myString: ".$myString;
    

    Prints the transformed string,

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

    Let me know if this is what you wanted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条