Jump to content

How do we tokenise a string?


g_p_java

Recommended Posts

Hello,

 

i would like to tokenise a string e.g. $x = 'How are you today?';

 

Output:

How

are

you

today?

 

Then i would like to take as output the characters every string contains:

 

How -> H o w

are -> a r e

you -> y o u

etc

and store every char in an array.

 

What shall i do?

 

Thanks in advance!  ;)

Link to comment
https://forums.phpfreaks.com/topic/143618-how-do-we-tokenise-a-string/
Share on other sites

Hm..i used strtok and i tokenise the string like

 


$ip = $_SERVER["REMOTE_ADDR"];  


$tok = strtok($ip, ".");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(".");
}


 

How  am i supposed to divide each $tok into the characters it contains?

Wierd thing to do, but you'll need two loops;

 

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$splitIp = explode(".", $ip);
foreach($splitIp as $ipPart){
for($i=0;$i<strlen($ipPart);$i++){
	$charArray[] = $ipPart[$i];
}
}
var_dump($charArray);
?>

 

not tested but looks ok :)

Wierd thing to do, but you'll need two loops;

 

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$splitIp = explode(".", $ip);
foreach($splitIp as $ipPart){
for($i=0;$i<strlen($ipPart);$i++){
	$charArray[] = $ipPart[$i];
}
}
var_dump($charArray);
?>

 

not tested but looks ok :)

 

Couldn't you do this?

 

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$splitIp = explode(".", $ip);
$charArray = array();
foreach($splitIp as $ipPart){
       $charArray = array_merge($charArray, str_split($ipPart));
}
var_dump($charArray);
?>

 

Seems a bit easier without messing with the loop :)

Wierd thing to do, but you'll need two loops;

 

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$splitIp = explode(".", $ip);
foreach($splitIp as $ipPart){
for($i=0;$i<strlen($ipPart);$i++){
	$charArray[] = $ipPart[$i];
}
}
var_dump($charArray);
?>

 

not tested but looks ok :)

 

Couldn't you do this?

 

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$splitIp = explode(".", $ip);
$charArray = array();
foreach($splitIp as $ipPart){
       $charArray = array_merge($charArray, str_split($ipPart));
}
var_dump($charArray);
?>

 

Seems a bit easier without messing with the loop :)

 

Yea that is a little easier ;)

Well if it's strings filled with words you could do...

 

<?php

$x = 'How are you today?';

$out = array_map ( 'str_split', array_combine ( ( $words = str_word_count ( $x, 1 ) ), $words ) );

print_r ( $out );

?>

 

Not recommend (it would overwrite repeated words), but it should work otherwise...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.