Search code examples
phparraysstringsanitization

Remove HTML tags from strings in a flat array then join with commas


I have an array that contains a set of links as strings e.g.

[1] => "<a href = 'this.html'> This </a>"
[2] => "<a href = 'that.html'> That </a>"
[3] => "<a href = 'other.html'> Other </a>"

What is the easiest way to echo out just the text separated by comas? e.g. so it displays:

This, That, Other

Solution

  • You'll require the use of two functions, implode and strip_tags.

    $data = array (
      "<a href='this.html'>This</a>",
      "<a href='this.html'>That</a>",
      "<a href='this.html'>Other</a>"
    );
    
    echo strip_tags (implode (", ", $data));
    

    This, That, Other
    

    Links to documentation

    • implode

      This function will glue together the elements of the array passed as second parameter with the "glue" specified as the first. implode (":", array (1,2,3)) will result in "1:2:3"

    • strip_tags

      This function will remove the xml-elements (tags) found in the string passed as first parameter.