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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?