skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. The 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>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search