tags:

views:

39

answers:

2

I want to take plain text and wrap every word with an element

like so

<v>Archer</v> <v>aŭtomobilis</v> <v>fore</v> <v>de</v> <v>antaŭkristnaska</v> <v>festo</v> <v>en</v> <v>suda</v> <v>apudurbo</v>. <v>Malgraŭ</v>

What is the best way to do this in php thanks.

+3  A: 
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "<v>$tok</v>";
    $tok = strtok(" \n\t");
}
McGin
I think you'll replace symbols like `.` as well
Ivan Nevostruev
+2  A: 

Use preg_replace to find words and replace them with wrapped version:

$string = preg_replace('/(\w+)/', '<v>\1</v>', $string);

Regular expression works as following:

  • / is delimeter of regular exprtession, everything between /.../ is expression itself
  • (...) - is capturing group which saves result of inner regexp into special array
  • \w - means word character
  • \w+ - means 1 or more word characters

In replacement \1 means value of first group saved in regexp.

Ivan Nevostruev
Can you please explain to me what '/(\w+)/g' is telling the computer,(?whitespace = (/w+) and /g = what? and I get '<v>\1</v>' but why the 1, can I wrap every other word in something else?
Klanestro
\w = any word character (a-z, A-Z, 0-9, _)\w+ = any word character one or more times(\w+) capture any word character one or more times in a backreference/(\w+)/g = make the search global on the stringThe \1 in the second argument tells preg_replace to put the matched string from (\w+) into <v>here</v>
Johrn
@Johrn: `/g` is not listed on the PHP Manual, care to explain what it does in a little more detail?
Alix Axel
I've removed `/g`. It's not needed in PHP.
Ivan Nevostruev
didn't realize that PHP didn't need /g. oh well
Johrn