(PHP)用数组值

时间:2016-03-08 10:36:12

标签: php arrays regex

我有一个正则表达式,可以在两个方括号中找到文本:

preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches);

从名为row的数组中,我需要获取与正则表达式匹配的键的值,并将其替换为$body字符串。

例如,

foreach ($matches[0] as $array_key) {
    row->$array_key;
    //The value at the specific key, but I need to take this value and put it back in the spot where its key was found in the body string

}

2 个答案:

答案 0 :(得分:0)

试试这个:

$body = '[testtext][othertext]';
preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches);

foreach($matches[0] as $key => $value)
{
    $values[] = $value;
}
print_r($values);

结果是:

Array ( [0] => testtext [1] => othertext )

这是你想要的吗?

答案 1 :(得分:0)

这对我有用

 <pre>
    <?php 
     $b = "Name: some sample text [] and some other [] and the thired one [] and 4 [] putting it on end[] and some thing after";
     preg_match_all("/(?<=\[).+?(?=\])/", $b, $m);

     $str = substr($b, 0,strpos($b, '[')+1);

     $row= array("val1","val2","val3","val4","val5");

     foreach($row as $k => $value) {

        $afterstr =  (  $k <=  count($m[0])-1 ) ?  $m[0][$k] : ""; // because the last ']' is not in $m array so we have to handle that
        $str .= $value . $afterstr ;
    }

    $str .= strrchr($b,']'); // appending after the last ']' text
    var_dump($str);

string(135)“名称:一些示例文本[val1]和其他一些[val2]和thired [val3]和4 [val4]把它放在最后[val5]和之后的一些东西