可以分词吗?

我想问一下是否可以

"Keyboard"在PHP中将一个单词剪切成多个字符串?

我希望只要有 / 就切断字符串。


例子:


String: "Key/boa/rd"

现在我希望剪切结果如下所示:


String1: "Key"

String2: "boa"

String3: "rd"


神不在的星期二
浏览 172回答 3
3回答

ibeautiful

您可以使用 PHP 的爆炸功能。所以,如果你的字符串是"Key/boa/rd",你会这样做:explode('/', 'Key/boa/rd');并得到:[     "Key",     "boa",     "rd",]您的问题尚不清楚,但如果您不想要一个数组(而是想要变量),您可以像这样使用数组解构:[$firstPart, $secondPart, $thirdPart] = explode('/', 'Key/boa/rd');但是,如果字符串只有一个/,那么这种方法可能会导致抛出异常。

红颜莎娜

Nathaniel 的回答假设您的原始字符串包含 / 字符。您可能只在示例中使用了这些,并且您希望将字符串拆分为等长的子字符串。它的功能是 str_split ,它看起来像:$substrings = str_split($original, 3);这会将字符串 $original 拆分为一个字符串数组,每个字符串的长度为 3(如果它不均分,则最后一个除外)。

隔江千里

您可以逐个字符地遍历行,检查您的分隔符。<?php$str = "Key/boa/rd";$i = $j = 0;while(true){&nbsp; &nbsp; if(isset($str[$i])) {&nbsp; &nbsp; &nbsp; &nbsp; $char = $str[$i++];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; if($char === '/') {&nbsp; &nbsp; &nbsp; &nbsp; $j++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; if(!isset($result[$j])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[$j] = $char;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[$j] .= $char;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}var_export($result);输出:array (&nbsp; &nbsp; 0 => 'Key',&nbsp; &nbsp; 1 => 'boa',&nbsp; &nbsp; 2 => 'rd',&nbsp; )然而,explode、preg_split 或 strtok 可能是想要拆分字符串时的 goto Php 函数。
打开App,查看更多内容
随时随地看视频慕课网APP