php基于单词拆分字符串

时间:2014-10-28 13:40:49

标签: php arrays string

我有一个像这样的PHP字符串

$string = 'Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem.';

我正在尝试将此字符串拆分为2(数组是可接受的)我正在尝试拆分,因此我的第一个字符串包含Sale Center Hours之前的所有内容,第二个字符串包含Sale Center Hours以及之后的所有内容。

5 个答案:

答案 0 :(得分:1)

你是否正在寻找这样的结果?如果是,您可以使用以下代码:

Array ( 
    [0] => Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. 
    [1] => Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem. 
)

此代码:

<?php
$string = 'Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem.';

$split_by = 'Sales Center Hours';
$split_data = explode($split_by, $string);
$split_data[1] = $split_by . $split_data[1];
print_r ($split_data);
?>

如果在文本中找不到$ split_by,则会给我们带来意想不到的结果。为了优雅地管理它,你可以这样做:

<?php
$string = 'Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem.';

$split_by = 'Bad text';
$split_data = explode($split_by, $string);

// confirm that the string was split into two. If it did, 
// add the split_by text to the front of the 2nd item (index 1)
if (count($split_data) === 2) {
    $split_data[1] = $split_by . $split_data[1];
}

// do something with the text
print_r ($split_data);
?>

答案 1 :(得分:1)

Regexp版本

preg_match( '/(.*)\s+(Sales Center Hours.*)/', $string, $matches );

echo( $matches[1] ); // before
echo( $matches[2] ); // after

答案 2 :(得分:0)

哟可以使用php函数split http://php.net/manual/es/function.split.php,你必须识别模式

答案 3 :(得分:0)

您可以使用展开字符串,然后将用于爆炸的字符串添加到数组元素中。

<?php
$stringToSplit = "Sales Center Hours";
$string = 'Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem.';
$arr = explode($stringToSplit, $string);
$arr[1] = $stringToSplit . $arr[1];
print_r($arr)
?>

答案 4 :(得分:0)

&#34;爆炸&#34;功能可以做到......如下所示:

$string = "Nunc sagittis in orci in pharetra. Mauris orci mauris, tincidunt in nisi quis, bibendum facilisis lectus. Sales Center Hours Donec nec tristique neque. In hac habitasse platea dictumst. Cras sit amet mauris lorem.";
$separator="Sale Centre Hours";
$results=explode($separator,$string);
$firstString=$results[0];
$secondString=$separator.$results[1];