Praneeth Madushan Praneeth Madushan - 6 months ago 11
PHP Question

PHP how to store words of a sentence into a string without explode

I'm making a php tag script for my website.
I have completed the code, but I'm afraid my code is too long.

Can my code be more simple and short?



<?php
include("admin/apps/site-settings.php"); // database connection
$albumq = mysql_query("select * from albums order by rand() limit 20");
while($album = mysql_fetch_array($albumq)){
$name_a = str_replace("&apos;s","",$album['name']);
$name_b = str_replace("&quot;","",$name_a);
$name_c = str_word_count($name_b, 1);
?>
<?php if(!empty($name_c[0])){?>
<a href="search-<?php echo $name_c[0];?>.html">
<div class="tag">
<?php echo $name_c[0];?>
</div>
</a>
<?php }?>
<?php if(!empty($name_c[1])){?>
<a href="search-<?php echo $name_c[1];?>.html">
<div class="tag">
<?php echo $name_c[1];?>
</div>
</a>
<?php }?>
<?php if(!empty($name_c[2])){?>
<a href="search-<?php echo $name_c[2];?>.html">
<div class="tag">
<?php echo $name_c[2];?>
</div>
</a>
<?php }?>
<?php if(!empty($name_c[3])){?>
<a href="search-<?php echo $name_c[3];?>.html">
<div class="tag">
<?php echo $name_c[3];?>
</div>
</a>
<?php }?>
<?php if(!empty($name_c[4])){?>
<a href="search-<?php echo $name_c[4];?>.html">
<div class="tag">
<?php echo $name_c[4];?>
</div>
</a>
<?php }?>
<?php if(!empty($name_c[5])){?>
<a href="search-<?php echo $name_c[5];?>.html">
<div class="tag">
<?php echo $name_c[5];?>
</div>
</a>
<?php }?>




Output in the website:

Output

I'm running it on localhost so I can't provide a link at the moment.

Answer
<?php
include("admin/apps/site-settings.php"); // database connection
$albumq = mysql_query("select * from albums order by rand() limit 20");
while($album = mysql_fetch_array($albumq)){
    $name_a = str_replace("&apos;s","",$album['name']);
    $name_b = str_replace("&quot;","",$name_a);
    $name_c = str_word_count($name_b, 1);

    foreach ($name_c as $value)
    {
        if (!empty($value))
        {
            echo "
            <a href='search-{$value}.html'>
                <div class='tag'>
                    {$value}
                </div>
            </a>";
        }
    }
}
?>
Comments