Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将字符串分隔为不同字符串的php函数?_Php - Fatal编程技术网

将字符串分隔为不同字符串的php函数?

将字符串分隔为不同字符串的php函数?,php,Php,假设我这里有一个字符串:$string='你好,我叫尼古拉斯·凯奇' 我想将这些单词分成不同的字符串,如下所示: $word1 = 'hello'; $word2 = 'my'; $word3 = 'name'; $word4 = 'is'; $word5 = 'nicholas cage'; <?php $target = 'Hello my name is "Nicholas Cage"'; $pattern = '/"[^"]*"|\S+/'; $matches = array()

假设我这里有一个字符串:$string='你好,我叫尼古拉斯·凯奇'

我想将这些单词分成不同的字符串,如下所示:

$word1 = 'hello';
$word2 = 'my';
$word3 = 'name';
$word4 = 'is';
$word5 = 'nicholas cage';
<?php
$target = 'Hello my name is "Nicholas Cage"';
$pattern = '/"[^"]*"|\S+/';
$matches = array();
preg_match_all($pattern,$target,$matches);
var_dump($matches);
?>
对于前4个单词,我可以使用explode。但是我怎么处理word5呢?我希望名字和姓氏是一个字符串。

您可以执行$bits=explode'',$string;,这会给你:你好,我的名字是,尼古拉斯,凯奇,但它无法知道尼古拉斯凯奇是一个实体

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


编辑:我看到您现在引用了nicholas cage,在这种情况下,您可以使用正则表达式,类似于:preg_match'/[\s].?$1/',$str,$matches

这是通过解析完成的。谷歌递归下降。

您可以使用以下正则表达式:

/"[^"]*"|\S+/
您可以这样使用它:

$word1 = 'hello';
$word2 = 'my';
$word3 = 'name';
$word4 = 'is';
$word5 = 'nicholas cage';
<?php
$target = 'Hello my name is "Nicholas Cage"';
$pattern = '/"[^"]*"|\S+/';
$matches = array();
preg_match_all($pattern,$target,$matches);
var_dump($matches);
?>

这可以使用regexp完成:

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

查找与以下内容匹配的任何内容: [^]*-双引号中的任何内容 \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
)

您还可以使用string函数:如果需要的话。只需调用分隔符,而不是

示例:$array=str_getcsv$string

这对我有用

$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);

返回nicholas cage

我是否可以使用其他函数先搜索后搜索最后一个并以某种方式将其提取为字符串?很好,当我的限制解除时,我将在9分钟内+1:代码量最短,答案很好。我测试确定,它工作完美!如果您的PHP>5.3这对任何PHP版本都适用,则效果非常好。。我的选择看一看我的答案大多数答案都有用那么你真正需要什么?