Search code examples
phphtmltextstripstrip-tags

How would one strip text before and after a certain html tag


Basically I want to take something like:

textheretextheretexthere
<table>
<tr><td>heres some stuff</td><td>and some morestuff</td></tr>
</table>
moretextheremoretexthere

and remove all the texthere and moretext here just leaving the table


Solution

  • You need to find <table> position with strpos and then use substr to remove the text to this point.and then the same for </table>

    $string = 'textheretextheretexthere<table><tr><td>heres some stuff</td><td>and some morestuff</td></tr></table>moretextheremoretexthere';
    
    $table_pos = strpos($string,'<table>');
    $string = substr($string,$table_pos);
    //Your string now is <table><tr><td>heres some stuff</td><td>and some morestuff</td></tr></table>moretextheremoretexthere
    
    $endtable_pos = strpos($string,'</table>')+8;//added 8 so i wont exclude </table>
    $clean_string = substr($string,0,$endtable_pos);
    //Your string now is <table><tr><td>heres some stuff</td><td>and some morestuff</td></tr></table>
    

    Of course this is not perfect at all,i know but you got the hint,you can work on improving it and maybe end up with a function that helps you solve your problem.