admin管理员组文章数量:1122832
I am building an HTML element from a PHP array inside a foreach loop:
echo '<li><a href="#" onclick="return filterByCategory("'.ltrim($categoryID).'");">'.$categoryName.'</a></li>';
results in the HTML output:
<a href="#" onclick="return filterByCategory(" 514ac53a-a047-45eb-b89b-05f012fb2b5b");">Adults</a>
It always adds a space, even with ltrim (I've tried trim and htmlspecialcharacters too)
Within the same loop, var_dump outputs:
string(36) "514ac53a-a047-45eb-b89b-05f012fb2b5b"
so it feels like the input data is without a space. It is doing it to every value field in the array. I don't understand.
I am building an HTML element from a PHP array inside a foreach loop:
echo '<li><a href="#" onclick="return filterByCategory("'.ltrim($categoryID).'");">'.$categoryName.'</a></li>';
results in the HTML output:
<a href="#" onclick="return filterByCategory(" 514ac53a-a047-45eb-b89b-05f012fb2b5b");">Adults</a>
It always adds a space, even with ltrim (I've tried trim and htmlspecialcharacters too)
Within the same loop, var_dump outputs:
string(36) "514ac53a-a047-45eb-b89b-05f012fb2b5b"
so it feels like the input data is without a space. It is doing it to every value field in the array. I don't understand.
Share Improve this question asked Nov 22, 2024 at 16:43 andyg1andyg1 1,5433 gold badges14 silver badges21 bronze badges 4 |2 Answers
Reset to default 1The problem is that you're using "
to delimit both the onclick
attribute and the string argument to the function. The result is that the double quote that begins the function argument is terminating the attribute, so the argument becomes a separate attribute.
Use single quotes for one of them.
echo '<li><a href="#" onclick="return filterByCategory(\''.ltrim($categoryID).'\');">'.$categoryName.'</a></li>';
I would check and see that your string really has what you think it has.
The "space" might be a non-printable character that is not identified as a proper space by ltrim
but that displays as a space.
Try something like this and see if it does not solve your problem:
$$categoryID = preg_replace('/[^[:print:]]/', '', $$categoryID);
More details here: How to remove all non printable characters in a string?
本文标签: PHP echo function is adding whitespace at the start of a string without whitespaceStack Overflow
版权声明:本文标题:PHP echo function is adding whitespace at the start of a string without whitespace - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736302264a1931472.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
onclick="return filterByCategory("
and spaces are required syntax between element attributes. – admcfajn Commented Nov 22, 2024 at 16:51