Log in

View Full Version : i'm stuck in counting new lines PHP


pc
2012-04-18, 07:05 PM
So I have a $ckeys['keywords'] string, (extract from head meta keywords ) that pretty much looks like this:

word
word
word
word
and so on, depends how many keywords there is.

Now I wrapped every new line into a separate <p> paragraph.

<?php echo "<p id='cell1'>" . str_replace("\n", "</p><p id='cell1'>", $ckeys['keywords']) . "</p>"; ?>

What I would like to have is to have a counter for each new line and use this counter for id='cell1' so I could have id='cell1', id='cell2', id='cell3' ...

Anyone ?



:)

cd34
2012-04-18, 08:34 PM
<?php

$ckeys['keywords'] = array('word1','word2','word3','word4');
$loop = 1;
foreach ($ckeys['keywords'] as $word) {
printf("<p id='cell%d'>%s</p>\n", $loop, $word);
$loop++;
}

flowersgone
2012-04-19, 07:54 AM
I think sparky's answer is good but addresses a slightly different question. Perhaps this is closer to the question as posed:

<?php
$ckeys = array();
$ckeys['keywords'] = <<<EOT
word1
word2
word3
word4
EOT;

foreach (explode("\n", $ckeys['keywords']) as $i => $w) {
$id = "cell" . ($i+1);
echo "<p id='$id'>$w</p>\n";
}
?>

fg

cd34
2012-04-19, 12:13 PM
I think sparky's answer is good but addresses a slightly different question. Perhaps this is closer to the question as posed:

You are correct, I assumed that the words were actually in his keywords array.

pc
2012-04-19, 02:59 PM
thank you guys |thumb
I'll test this tonight.

pc
2012-04-19, 04:34 PM
I already had keywords in array. But it works. Both cd34 and flowersgone without array works. Thanks again.