在 php 中将句子转换为单词数组,而无需使用爆炸或拆分方法



我正在尝试在不使用爆炸或拆分方法的情况下将字符串转换为数组。

例如:

$input = "I am a developer";

我想得到:

$output = ['I','am','a','developer']

我试过了

<?php
$a = "I am a developer";
$currentindex = 0;
$output=array();
for($i=0;$i<strlen($a);$i++){
if($a[$i] == " "){
$temp = substr($a,$currentindex,$i);
$output[]=$temp;
$currentindex = $i+1;
}
}
print_r($output);

主要问题是,当你调用substr()时,第三个参数是你想要的字符串的长度而不是位置,所以只需从中减去$currentindex......

$temp = substr($a, $currentindex, $i - $currentindex);

您还缺少最后一部分,因此在循环添加之后(在这种情况下,您可以只获取字符串的其余部分(...

$output[] = substr($a, $currentindex);

这是一个没有任何字符串函数的替代版本。它有一个$currentWord字符串,并继续构建它,直到它到达一个空格,然后将其重置为空字符串,依此类推:

$text = 'I am a developer';
$words = [];
$currentWord = '';
for ($pos = 0, $length = strlen($text); $pos < $length; $pos++) {
if ($text[$pos] === ' ') {
$words[] = $currentWord;
$currentWord = '';
}
else {
$currentWord .= $text[$pos];
}
}
$words[] = $currentWord;
print_r($words);

演示:https://3v4l.org/F8VIi

注意:显然它不处理多个空格和其他特定情况,我愿意保持它的基本。

不使用explode()split()似乎是一个相当武断的要求,但由于这是您明确禁止的唯一两个函数,因此还有其他选项不需要手动迭代:

$array = preg_split('/s+/', $input)

或:

$array = str_getcsv($input, ' ');

输出

Array
(
[0] => I
[1] => am
[2] => a
[3] => developer
)

PHP确实有一个专门用于此的函数。

$input = "I am a developer";
$words = str_word_count($input, 1);

将输出

array(4( { [0] => 字符串(1( "I" [1] => 字符串(2( "am" [2] => 字符串(1( ">

a" [3] =>



字符串(9( "开发人员"}




最新更新