如何去除搜索结果link中第二个词前的空格?

How to remove spaces in front of the second words in search result link?

我正在尝试为文章创建动态可搜索关键字。 我用 + 替换空格并生成 links 就像 google 做的例子: search?q=text1+text2+text 我的代码首先生成 link 与示例中的 link 相同, 但是在第二个 link 前面添加 + 像这样:

Fisrt Link (which is what I want):

search?q=text1+text2+text

Second Link (Which is not right):

search?q=+text1+text2+text

?q=+text

之间添加一个 +

how can I remove that space from in front of the second keyword ?

我尝试了几种方法,但都做了不同的事情都接受了我想要的。

这是我的代码:

$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

trim 函数删除字符串开头和结尾的空格。

插入到您未进一步更改的代码中:

$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";
}