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

报告相同问题?