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.
2
Answers
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:
More details here: How to remove all non printable characters in a string?
The problem is that you’re using
"
to delimit both theonclick
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.