如何从括号中提取数据并在laravel中替换

时间:2018-03-08 06:01:28

标签: php

我的字符串是

"invoice = [[invoice_no]]
customer = [[customer]]
item = [[item]]"

我怎样才能使用上层字符串来隐藏以下内容?

"invoice = " $data->invoice_no
"customer = " $data->customer
"item = " $data->item

1 个答案:

答案 0 :(得分:0)

我已经为同一类型的解析创建了一个函数,它通过提供{{item}}等数据来替换$data['item']。这是示例,您可以根据您的要求进行更改。

<?php
    function putValuesInHTML($html_form,$reportData){
        preg_match_all('/{{([A-Za-z0-9_ ]+?)}}/', $html_form, $fields);
        $arrInHtml = array();
        $valsForHtml = array();
        foreach ($fields[1] as $key => $value) {
            if(isset($reportData[$value])){
                $arrInHtml[] = "{{".$value."}}";
                $valsForHtml[] = $reportData[$value];
            }
        }
        $result = str_replace($arrInHtml,$valsForHtml,$html_form);
        /*Eval start*/
        preg_match_all('/{{=([A-Za-z0-9+\-\/{}* ]+?)=}}/', $result, $evals);
        $arrInHtml = array();
        $valsForHtml = array();
        foreach ($evals[1] as $key => $value) {
            $eval = "00";
            $arrInHtml[] = "{{=".$value."=}}";
            eval("\$eval= ".$value.";");
            $valsForHtml[] = $eval;
        }
        $reportHTML = str_replace($arrInHtml,$valsForHtml,$result);
        return $reportHTML;
    }

$str = "invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}";
$data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"]    ;
$newStr = putValuesInHTML($str,$data);
echo $newStr;

?>

Live demo

输入:

invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}

$data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"]的输出:

invoice = 111
customer = Niklesh Raut
item = iphone