从字符串文本中获取值时出错?

时间:2012-04-17 10:15:48

标签: php

我有一个来自文字:

$text = 'abc def abc ghi abc jkl';
$search = 'abc';
$regex = '/'.trim($search).'/ism';
if(preg_match_all($regex, $text, $tmp)) {
   $array_key = $tmp[0];
   foreach($array_key as $ak) {
       echo $ak[1];
   }
}

当我回显$ ak [1]时,结果是 b ,我希望结果是 abc ,如何修复它

abc def abc ghi abc jkl

4 个答案:

答案 0 :(得分:1)

你的循环中echo $ak;呢?

$ak[1]是匹配中的第二个字符,因此产生b

答案 1 :(得分:1)

好吧,$tmp将包含正则表达式中所有字段的数组。然后这些数组将包含这些字段的所有值。

您的代码有效执行的操作是$ak = $tmp[0][$x] = "abc",当您执行$ak[1]时,您会比数组实际拥有的级别更低一级并获得"abc"[1] = "b"

我认为你想改为echo $ak;

答案 2 :(得分:0)

if(preg_match_all($regex, $text, $tmp)) {
   $array_key = $tmp[0];
   echo $array_key[1];
}

答案 3 :(得分:0)

I am trying to discuss within your code. I hope its will help

<?php
$text = 'abc def abc ghi abc jkl';
$search = 'abc';
$regex = '/'.trim($search).'/ism';
if(preg_match_all($regex, $text, $tmp)) 
{
  $array_key = $tmp[0];

  /*Test using print_r($tmp); 
    then you will find result: Array( [0] => Array ( [0] => abc [1] => abc [2] =>      
     abc) ) 
   If you want to test/print first array value then echo $array_key[0]; result is: abc
   Similarly for $array_key[1] or $array_key[2] result is abc
   That means your array contains 3 same value
   */

   foreach($array_key as $ak) 
   {
    /*If you use echo $ak[1]; then it will print b because in foreach loop $ak value   
    is:  abc 
    You can't print only abc in foreach loop. To print abc you don't need to use   
    foreach loop. Just use echo $array_key[0]; 
   */ 
   }
  }
  ?>

  Maybe your expected code is:
  <?php
    $text = 'abc def abc ghi abc jkl';
    $search = 'abc';
    $regex = '/'.trim($search).'/ism';
    if(preg_match_all($regex, $text, $tmp)) 
    {
     $array_key = $tmp[0];
     echo $array_key[0];
    }
   ?>
  Output: abc