使用PHP将字符串拆分成两半(可识别Word) [英] Split Strings in Half (Word-Aware) with PHP

查看:487
本文介绍了使用PHP将字符串拆分成两半(可识别Word)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串拆分为两半,并且不应将其拆分为一个单词.

I'm trying to split strings in half, and it should not split in the middle of a word.

到目前为止,我想出了99%可以正常工作的以下内容:

So far I came up with the following which is 99% working :

$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";
$half = (int)ceil(count($words = str_word_count($text, 1)) / 2); 
$string1 = implode(' ', array_slice($words, 0, $half));
$string2 = implode(' ', array_slice($words, $half));

这确实有效,可以根据字符串中的单词数将任何字符串正确地分成两半.但是,它将删除字符串中的所有符号,例如对于上面的示例,它将输出:

This does work, correctly splitting any string in half according to the number of words in the string. However, it is removing any symbols in the string, for example for the above example it would output :

The Quick Brown Fox Jumped
Over The Lazy Dog

我需要在分割后将所有符号如:和/保留在字符串中.我不明白为什么当前代码会删除符号...如果您可以提供替代方法或修复此方法以不删除符号,将不胜感激:)

I need to keep all the symbols like : and / in the string after being split. I don't understand why the current code is removing the symbols... If you can provide an alternative method or fix this method to not remove symbols, it would be greatly appreciated :)

推荐答案

在查看示例输出后,我注意到所有示例均已关闭,如果字符串的中间位置在一个单词中,则我们对string1的投入较少然后再给更多.

Upon looking at your example output, I noticed all our examples are off, we're giving less to string1 if the middle of the string is inside a word rather then giving more.

例如,The Quick : Brown Fox Jumped Over The Lazy / Dog的中间是The Quick : Brown Fox Ju,它位于一个单词的中间,第一个示例为string2提供了拆分单词;最下面的示例为string1分配了分隔词.

For example the middle of The Quick : Brown Fox Jumped Over The Lazy / Dog is The Quick : Brown Fox Ju which is in the middle of a word, this first example gives string2 the split word; the bottom example gives string1 the split word.

少给分割词上的string1

$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";

$middle = strrpos(substr($text, 0, floor(strlen($text) / 2)), ' ') + 1;

$string1 = substr($text, 0, $middle);  // "The Quick : Brown Fox "
$string2 = substr($text, $middle);  // "Jumped Over The Lazy / Dog"

为拆分词的string1提供更多

$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";

$splitstring1 = substr($text, 0, floor(strlen($text) / 2));
$splitstring2 = substr($text, floor(strlen($text) / 2));

if (substr($splitstring1, 0, -1) != ' ' AND substr($splitstring2, 0, 1) != ' ')
{
    $middle = strlen($splitstring1) + strpos($splitstring2, ' ') + 1;
}
else
{
    $middle = strrpos(substr($text, 0, floor(strlen($text) / 2)), ' ') + 1;    
}

$string1 = substr($text, 0, $middle);  // "The Quick : Brown Fox Jumped "
$string2 = substr($text, $middle);  // "Over The Lazy / Dog"

这篇关于使用PHP将字符串拆分成两半(可识别Word)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆