سؤال

I'm using this string to get what's needed:

echo "<div id=\"lot\">".$table->children(2)->children(0)->plaintext."</div>";

And I get the result: 01 02 03 04 05 06 10 15 17 27 31 etc.

What I need is to add <div id=\"new\"></div> to each number.

<div id=\"new\">01</div> <div id=\"new\">02</div> etc etc.

I tried to use the code below but it doesn't work

 $table = $box_rezult->find("table.last-d", 0);
        $results = $table->children(2)->children(0)->plaintext;
        $string = $results;
        $var1 = str_replace(" ", "<div id=\"new\"> </div>", $string);
        echo $var1;

I would appreciate any help, thanks!

Thanks to everyone!!

هل كانت مفيدة؟

المحلول

explode() the string to an array, then implode() it:

echo '<div class="new">' . implode('</div><div class="new">', explode(' ', $string)) . '</div>';

I've changed id to class as id's must be unique.

Demo

نصائح أخرى

For your use case you need to flip tags to get a separator and pre- and append one more:

$var1 = "<div id=\"new\">" . str_replace(" ", "</div> <div id=\"new\">", $string) . "</div>";

Assuming that $string contains all the numbers you want, you can explode it and put each element you want to have in tags for each number and then apply it to string, using a loop (or implode, as suggested):

$numbers = explode(" ", $string);
$var1 = ""; 
foreach($numbers as $number){
  $var1 .= "<div id=\"new\">".$number."</div>";
}

Also, please take into consideration about id attribute uniqueness. Use class attribute instead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top