如何在php中查找字符串或数组中的关键字?

时间:2012-01-25 21:50:06

标签: php arrays search

我有一个字符串:

$string = "test1 - test2 - kw: test - key: 123 - test5";

我试图得到这个结果:

kw = test;
key = 123;

我试过吐出字符串:

$array = explode("-", $str );
print_r($array);

结果是:

Array
(
    [0] =>  test1 
    [1] =>  test2
    [2] =>  kw: test
    [3] =>  key: 123
    [4] =>  test5
)

从这里我想做点什么:

$str = 'kw:';
if ( in_array ( $str , $array ) ) {
    echo 'It exists';
} else {
    echo 'Does not exist';
}

$kw = array_search('kw:', $array ); 

但是$array是一个数组数组。

我不确定如何从这里开始。

任何想法?是否有另一种提取这些词的方法?

感谢

5 个答案:

答案 0 :(得分:1)

使用preg_match变得非常简单:

$string = "test1 - test2 - kw: test - key: 123 - test5";
$results = preg_match('/.*?(kw: (.*?) - )(key: (.*?) -).*/', $string, $matches);
var_dump($matches);

应返回与您要查找的内容相对应的匹配数组...

array(5) {
  [0]=>
  string(43) "test1 - test2 - kw: test - key: 123 - test5"
  [1]=>
  string(11) "kw: test - "
  [2]=>
  string(4) "test"
  [3]=>
  string(10) "key: 123 -"
  [4]=>
  string(3) "123"
}

有关正则表达式的更多信息(非常强大的工具):

http://www.regular-expressions.info/tutorial.html

答案 1 :(得分:1)

这是一个在

中查找子字符串kw:key:的循环
$string = "test1 - test2 - kw: test - key: 123 - test5";
$array = explode("-", $string);

foreach ($array as $part) {
  if (substr(trim($part), 0, 3) == 'kw:') {
    list($kw, $kwval) = explode(' ' , trim($part));
    echo "kw: $kwval\n";
  }
  if (substr(trim($part), 0, 4) == 'key:') {
    list($key, $keyval) = explode(' ' , trim($part));
    echo "key: $keyval\n";
  }
}


// Output:
// kw: test
// key: 123

答案 2 :(得分:1)

php > $string="test1 - test2 - kw: test - key: 123 - test5";
php > $pattern="/\ \-\ (\w+)\:\s([^\s]+)/";
php > echo preg_match_all($pattern,$string,$matches);
2
php > print_r($matches);
Array
(
    [0] => Array
        (
            [0] =>  - kw: test
            [1] =>  - key: 123
        )

    [1] => Array
        (
            [0] => kw
            [1] => key
        )

    [2] => Array
        (
            [0] => test
            [1] => 123
        )

)
php > 

答案 3 :(得分:1)

不优雅,但是:

$string = "test1 - test2 - kw: test - key: 123 - test5"; 

$array = explode(" - ", $string);

foreach ($array as $v) {
    if (strstr($v,"kw: ")) {
        $kw = substr($v,4);
    }
    if (strstr($v,"key: ")) {
        $key = substr($v,5);
    }
}

echo "kw = " . $kw;
echo "key = " . $key;

答案 4 :(得分:0)

看看substr()

http://php.net/manual/en/function.substr.php

你不必爆炸你的字符串