簡體   English   中英

在 PHP 中獲取數組值表單字符串模式

[英]Get array value form string pattern in PHP

我假設數組是

Array
(
            [0] => john
            [1] => robinson
            [2] => 27-08-1980
            [3] => football
            [4] => pizza

)

我想通過使用字符串模式從數組中獲取值
示例字符串模式(它也可以使用 html 代碼):

string = "{0} {1} birthday {2} <br /> Hobbie : {3}  <br /> favorite : {4}"

結果是

john robinson birthday 27-08-1980
Hobbie : football 
favorite : pizza

怎么解決

您可以使用vsprintf() ,但您必須將模板占位符更改為 %s。

$data = array(...); // your array
$template = '%s %s birthday %s <br /> Hobbie : %s  <br /> favorite : %s';
$result = vsprintf($template, $data);

使用preg_replace_callback()

$data = [
    0 => 'john',
    1 => 'robinson',
    2 => '27-08-1980',
    3 => 'football',
    4 => 'pizza',
];

$template = "{0} {1} birthday {2} <br /> Hobbie : {3}  <br /> favorite : {4}";

$string = preg_replace_callback(
    '/\{(\d+)\}/',
    function ($matches) use ($data) {
        return $data[$matches[1]];
    },
    $template
);

echo $string;

演示

preg_replace_callback將幫助您:

<?php
$array = array('john', 'robinson', '27-09-1980', 'football', 'pizza');
$string = "{0} {1} birthday {2} <br /> Hobbie : {3}  <br /> favorite : {4}";
$pattern = "/\{[0-9]\}/";

$newString = preg_replace_callback($pattern, function($matches) use ($array) {
    return $array[substr($matches[0],1,1)]; 
}, $string);

echo $newString;

以上返回:約翰羅賓遜生日 27-09-1980

愛好:足球

最喜歡的:披薩

$arr = array('john','robinson','27-08-1980', 'football','pizza');
$str = "{$arr[0]} {$arr[1]} birthday {$arr[2]} <br /> Hobbie : {$arr[3]}  <br /> favorite : {$arr[4]}";
echo $str;

你為什么不試試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM