php在div之前和comman之后获取字符串的一部分

时间:2017-08-09 07:34:12

标签: php string

请有人帮帮我吗?我只需要使用PHP在字符串中获取单词的一部分。在以下示例中,我需要从以下字符串中获取Kimberley一词:

13 Angel Street, El Toro Park, Kimberley <div Id='rentals' Class='rentals'>Agencies</div> <div Id='rentalsix' Class='rentals'>5</div>

我尝试了以下内容:

$searchaddress = 13 Angel Street, El Toro Park, Kimberley <div Id='rentals' 
Class='rentals'>Agencies</div> <div Id='rentalsix' Class='rentals'>5</div>;

preg_match('|<[^>]*rentals[^>]*>(.*?)<|', $searchaddress, $m);
$newvalue = $m[1];
echo htmlspecialchars($newvalue));

它可以工作,但它只能从字符串中获取单词Agenncies。我需要Kimbherley这个词。

3 个答案:

答案 0 :(得分:2)

我希望这会有所帮助。

  //this is your string.
    $text = '13 Angel Street, El Toro Park, Kimberley <div Id=\'rentals\' Class=\'rentals\'>Agencies</div> <div Id=\'rentalsix\' Class=\'rentals\'>5</div>';
    //find position of ',' from where you want to explode using strrpos
        $pos=strrpos($text,',',2);
    // explode string from given postion.
        $text=substr($text,$pos);
    //find the text that exist between ',' and  starting bracket of div '<'
        preg_match('#,(.*?)<#', $text, $match);
    // output
        var_dump( $match[1]);

答案 1 :(得分:0)

$exp = explode(' <div', $searchaddress );
$exp = explode(' ', $exp[0]);
$exp = $exp[count($exp)-1];

作为变种。

答案 2 :(得分:0)

要忽略HTML标记,请使用strip_tags PHP函数。 有关详细信息,请参阅此链接STRIPTAGS

如果您想在第一个div之前使用第一个字符串,请使用explode函数。

$searchaddress = 13 Angel Street, El Toro Park, Kimberley <div Id='rentals' 
Class='rentals'>Agencies</div> <div Id='rentalsix' Class='rentals'>5</div>;

strip_tags($searchaddress);

仅获取字符串的第一部分。

$str   =   explode("<div",$searchaddress);
echo $str[0];