Search code examples
phpphp-7

Remove empty < >


Is there a way to remove < > if it's empty?

the text can be; < > Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, < > when an <b>unknown printer</b> took <> a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries. < >

output should be; Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an <b>unknown printer</b> took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.


Solution

  • You could use preg_replace:

    $text = "<  > Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, < > when an <b>unknown printer</b> took <> a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries. <     >";
    $text = preg_replace('/<\s*\>/', '', $text);
    echo $text;
    

    Output:

     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,  when an <b>unknown printer</b> took  a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries. 
    

    Demo on 3v4l.org

    If you also want to clean up any multiple or hanging spaces (at beginning or end of line) from the removal of the empty <>, you can use this instead:

    $text = preg_replace(array('/<\s*\>/', '/\s+/', '/^\s|\s$/'), array('', ' ', ''), $text);
    

    Demo on 3v4l.org