Forum Moderators: coopster

Message Too Old, No Replies

Split string in words

I need a way to split a string in words

         

starefossen

11:21 pm on Dec 6, 2007 (gmt 0)

10+ Year Member



I need a way to split a string, devided by comma (,) og new line, but mainly by coma. The strin is a text with unlimited words and I need to display each word as a link.

Like, I want to split this text:
"This, is, a, text, with, 8, words"

What I want to do is display them like this:
<a href="page.php?id=This">This</a>, <a href="page.php?id=is">is</a>, <a href="page.php?a=this">a</a>, <a href="page.php?id=text">text</a>, <a href="page.php?id=with">with</a>, .... etc.

Dos anyone know how to make this possible?

PHP_Chimp

8:38 am on Dec 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




<?php
$in = "This, is, a, text, with, 8, words";
$split = preg_split('%[\s,]+%', $in);
echo '<pre>';
print_r($split);
echo '</pre>';
$op ='';
foreach ($split as $k => $v) {
$op.= "<a href=\"page.php?id=$v\">$v</a>\n";
}
echo $op;
?>

starefossen

12:51 pm on Dec 7, 2007 (gmt 0)

10+ Year Member



Thanks, however, there is one minor problem. It splits word where it is spaces and I need to preserve words that are supposed to stand together.

Like this:
Two word, three words here, etc

<a href="...">Two words</a>, <a href="...">Thre words here</a>,

d40sithui

4:09 pm on Dec 7, 2007 (gmt 0)

10+ Year Member



take the \s out of your preg_split function and it will only divide by the comma

PHP_Chimp

8:43 pm on Dec 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




<?php
$split = preg_split('%[\n,]+%', $in);
$op ='';
foreach ($split as $k => $v) {
$op.= "<a href=\"page.php?id=$v\">$v</a>\n";
}
echo $op;
?>

This will split by newline and comma. So hopefully that is what you are after.

starefossen

10:34 am on Dec 8, 2007 (gmt 0)

10+ Year Member



Thanks, :)

Is there any easy way to remove the space (%20) in the link of every word

Now it looks like this:
<a href="mypage.php?id=Two%20Words">Two Words</a> <a href="mypage.php?id=%20Three%20Words%20Here">Three Words Here</a>... ect

As you see the first link is right, but the second link gets a bit screwed... Not a big problem but if anyone have a sulution to it I would appriciate it.

Thanks for all help.. :)

gergoe

10:50 am on Dec 8, 2007 (gmt 0)

10+ Year Member



See the trim [php.net] function of php for removing leading and trailing spaces, or change the
%[\n,]+%
regular expression to
%[\n,]+\s*%
, so if there's a space after the separator, it will be considered as the part of the separator itself. By the way, you could alternatively use explode [php.net] for the same task (combined with trim), if you are not familiar with regular expressions.