I am trying to create dynamic searchable keywords for articles.
I am replacing spaces with + and generating links like google does example:
search?q=text1+text2+text
My code generate first link same as link in example,
but adding + to in front of the second link like this:
Fisrt Link (which is what I want):
search?q=text1+text2+text
Second Link (Which is not right):
search?q=+text1+text2+text
Adding a + between ?q=+text
how can I remove that space from in front of the second keyword ?
I tried several ways but all did different things accept what I want.
Here is my code:
$keywords = "text1 text2 text3, text4 text5 text6";
$tag = explode(",",$keywords);
for ($i=0; $i<count($tag);$i++){
$cat = str_replace(" ", "+", $tag[$i]);
echo "<a href=\"services/?q=".htmlspecialchars($cat)."\"><span itemprop=\"description\">".str_replace("+"," ", htmlspecialchars($cat))."</span></a>";
echo "<span class=\"separator\">|</span>\n";
}
I would like to generate all links like this:
search?q=text1+text2+text
The trim
function removes spaces from the begin and end of a string.
Inserted into your not further changed code:
$keywords = "text1 text2 text3, text4 text5 text6";
$tag = explode(",",$keywords);
for ($i=0; $i<count($tag);$i++){
$cat = str_replace(" ", "+", trim($tag[$i]));
echo "<a href=\"services/?q=".htmlspecialchars($cat)."\"><span itemprop=\"description\">".str_replace("+"," ", htmlspecialchars($cat))."</span></a>";
echo "<span class=\"separator\">|</span>\n";
}