Search code examples
phptrim

PHP: Trim to get rid of empty span


Referring to this comment.

$values = array("foo","bar");

var_dump($value) results in:

array (size=2)
  0 => string 'foo' (length=3)
  1 => string 'bar' (length=3)

Implode:

$value = "<span>".implode('</span>,<span>', $values)."</span>";

Now var_dump($value) results in:

string '<span>foo</span>,<span>bar</span>' (length=33)

Trim:

$value = trim($value,"<span></span>");

Now var_dump($value) results in:

string 'foo</span>,<span>bar' (length=20)

But it should still result in:

string '<span>foo</span>,<span>bar</span>' (length=33)

Solution

  • The trim function works at the character level, not the text or HTML tag level.

    When you do trim($value, "<span></span>") you're asking PHP to remove all leading and trailing characters that appear in the text <span></span>. This has the same result as doing trim($value, "/<>anps")

    You should probably use str_replaceinstead.

    Alternately, use array_filter to remove the blank entries in the array before you implode them.
    For example:

    $str = implode("</span>,<span>", array_filter($values, 'strlen'));