user12367845
user12367845

Reputation:

Is it possible to cut a word in parts? [PHP]


I would like to ask if it is possible to cut a word like
"Keyboard" in multiple strings, in PHP?
I want the string to be cut whenever a / is in it.

Example:

String: "Key/boa/rd"

Now I want that the cut result look like this:

String1: "Key"
String2: "boa"
String3: "rd"

Upvotes: 0

Views: 77

Answers (3)

Progrock
Progrock

Reputation: 7485

You can travel through the line character by character, checking for your delimeter.

<?php
$str = "Key/boa/rd";
$i = $j = 0;
while(true)
{
    if(isset($str[$i])) {
        $char = $str[$i++];
    } else {
        break;
    }

    if($char === '/') {
        $j++;
    } else {
        if(!isset($result[$j])) {
            $result[$j] = $char;
        } else {
            $result[$j] .= $char;
        }
    }
}
var_export($result);

Output:

array (
    0 => 'Key',
    1 => 'boa',
    2 => 'rd',
  )

However explode, preg_split or strtok are probably the goto Php functions when wanting to split strings.

Upvotes: 0

kainaw
kainaw

Reputation: 4334

The answer by Nathaniel assumes that your original string contains / characters. It is possible that you only used those in your example and you want to split the string into equal-length substrings. The function for that is str_split and it looks like:

$substrings = str_split($original, 3);

That will split the string $original into an array of strings, each of length 3 (except the very last one if it doesn't divide equally).

Upvotes: 0

Nathaniel Pisarski
Nathaniel Pisarski

Reputation: 308

You can use the PHP explode function. So, if your string was "Key/boa/rd", you would do:

explode('/', 'Key/boa/rd');

and get:

[
     "Key",
     "boa",
     "rd",
]

It's unclear from your question, but if you don't want an array (and instead would like variables) you can use array destructuring like so:

[$firstPart, $secondPart, $thirdPart] = explode('/', 'Key/boa/rd');

However, if the string only had one / then that approach could lead to an exception being thrown.

Upvotes: 1

Related Questions