我有一个字符串:
$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 );
但是CCD_ 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
这里有一个循环,用于查找中的子字符串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
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 >
不优雅,但:
$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;
看看substr()
http://php.net/manual/en/function.substr.php
你不必爆炸你的字符串