我需要分割特定格式的字符串,举例如下:
first action <img alt="" src="images/1.jpg"/> my photo我想这个字符串分成三部分first action 为一部分
<img alt="" src="images/1.jpg"/> 为一部分
my photo 为一部分前面的英语和后面的英语长短不定,我需要把img标签和前后的英语句子分开,分别存入变量之中,请问有什么好办法么?

解决方案 »

  1.   

    <?php
    $str = 'first action <img alt="" src="images/1.jpg"/> my photo';
    preg_match("/^(.+)(<.+>)(.+)/",$str,$matches);
    echo htmlspecialchars($matches[1])."<br />";
    echo htmlspecialchars($matches[2])."<br />";
    echo htmlspecialchars($matches[3])."<br />";
    ?>
      

  2.   

    <?php
    $str = 'first action <img alt="" src="images/1.jpg"/> my photo';
    preg_match("/^(.+)(<.+>)(.+)$/",$str,$matches);
    echo htmlspecialchars($matches[1])."<br />";
    echo htmlspecialchars($matches[2])."<br />";
    echo htmlspecialchars($matches[3])."<br />";
    ?>
      

  3.   

    <?php
    $string='first action <img alt="" src="images/1.jpg"/> my photo';
    $arr=explode("<",$string);
    $string2='<'.$arr[1];
    $brr=explode('>',$string2);
    //此时获得你所需要的三个字符串
    echo $arr[0];
    echo htmlspecialchars($brr[0]);
    echo '>'.$brr[1];
    ?>
      

  4.   

    <?php
    $string='first action <img alt="" src="images/1.jpg"/> my photo';
    $arr=explode("<",$string);
    $string2='<'.$arr[1];
    $brr=explode('>',$string2);
    //此时获得你所需要的三个字符串
    echo $arr[0];
    echo htmlspecialchars($brr[0]);
    echo '>'.$brr[1];
    ?>
      

  5.   

    <?php
    $string='first action <img alt="" src="images/1.jpg"/> my photo';
    $arr=explode("<",$string);
    $string2='<'.$arr[1];
    $brr=explode('>',$string2);
    //此时获得你所需要的三个字符串
    echo $arr[0];
    echo htmlspecialchars($brr[0]);
    echo '>'.$brr[1];
    ?>