2009-12-03 140 views
-1

可以说我在这里有这个字符串:$string = 'hello my name is "nicholas cage"'php函数将字符串分隔成不同的字符串?

我要分开的话到差异串这样的:

$word1 = 'hello'; 
$word2 = 'my'; 
$word3 = 'name'; 
$word4 = 'is'; 
$word5 = 'nicholas cage'; 

对于FHE第4个字,我可以使用爆炸。但我如何处理word5?我想要第一个和最后一个名字是一个字符串。

+0

最答案会工作那么你真的需要? – streetparade 2009-12-04 00:06:40

回答

0

你可以做$bits = explode(' ', $string);,这会给你:你好,我的名字是尼古拉斯,但是没有办法让它知道“尼古拉斯笼”是一个实体。

我不确定如何做你想做的事,你可能需要交叉引用字典数据库并加入任何未找到的单词。

编辑:我看现在你已经引用了“尼古拉斯·凯奇”,在这种情况下,你可以使用正则表达式,像这样:preg_match('/([\s"])(.*?)$1/', $str, $matches);

+0

我不能使用一些其他的功能,首先搜索“然后最后”,并以某种方式将其提取到一个字符串? – fayer 2009-12-03 23:41:03

0

多数民众赞成通过解析完成。谷歌“递归下降”。

+0

听起来有趣;-) – streetparade 2009-12-04 21:47:05

3

您可以使用正则表达式:

/"[^"]*"|\S+/ 

您可以使用它像这样:

<?php 
$target = 'Hello my name is "Nicholas Cage"'; 
$pattern = '/"[^"]*"|\S+/'; 
$matches = array(); 
preg_match_all($pattern,$target,$matches); 
var_dump($matches); 
?> 
+0

看看我的答案 – streetparade 2009-12-03 23:59:00

4

这是可以做到使用正则表达式:

$string = 'hello my name is "nicholas cage"'; 
preg_match_all('/(?:"[^"]*"|\S+)/', $string, $matches); 
print_r($matches[0]); 

它的工作原理如下:

  • 查找anythinh相匹配:
    • "[^"]*" - 任何在双引号
    • \S+ - 更多然后1非空格字符

但是,这一结果与报价。删除它们:

$words = array_map('remove_starting_ending_quotes', $matches[0]); 
print_r($words); 

function remove_starting_ending_quotes($str) { 
    if (preg_match('/^"(.*)"$/', $str, $matches)) { 
     return $matches[1]; 
    } 
    else { 
     return $str; 
    } 
} 

现在的结果看起来完全如预期:

Array 
(
    [0] => hello 
    [1] => my 
    [2] => name 
    [3] => is 
    [4] => nicholas cage 
) 
+0

这适用于任何PHP版本..我的选择 – 2009-12-03 23:58:31

7

你也可以使用字符串函数:str_getcsv,如果你想要的。只需调用分隔符“”而不是“,”;

例子:$array = str_getcsv($string, " ");

+1

不错,我会在9分钟内+1当我限制解除:)代码最短,很好的答案。我测试的确定,它完美的工作!如果你的PHP> 5.3, – 2009-12-03 23:51:12

+1

工作的很好 – 2009-12-03 23:58:01

0

这个工作对我来说

$word1 = 'hello'; 
$word2 = 'my'; 
$word3 = 'name'; 
$word4 = 'is'; 
$word5 = 'nicholas cage'; 

$my = array($word1,$word2,$word3,$word4,$word5); 


function word_split($str=array(),$words=1) { 
foreach($str as $str) 
{ 
    $arr = preg_split("/[\s]+/", $str,$words+0); 
    $arr = array_slice($arr,0,$words); 
    } 
    return join(' ',$arr); 
} 

echo word_split($my,1); 

回报尼古拉斯·凯奇