如何使用PHP在句子中拆分字符串?

时间:2013-07-12 14:08:43

标签: php string split

如何使用php拆分字符串中的单词并存储到两个不同的变量$ str1,$ str2

Input String : The encyclopedia project Wikipedia is the most famous wiki on the public web, but there are many sites running many different kinds of wiki software. Wikis can serve many different purposes both public and private, including knowledge management, notetaking, community websites and intranets. Some permit control over different functions (levels of access). For example, editing rights may permit changing, adding or removing material. Others may permit access without enforcing access control. Other rules may also be imposed to organize content.<div class="new">Some Text Here! </div> 

Output String : 

$str1 : The encyclopedia project Wikipedia is the most famous wiki on the public web, but there are many sites running many different kinds of wiki software. Wikis can serve many different purposes both public and private, including knowledge management, notetaking, community websites and intranets. Some permit control over different functions (levels of access). For example, editing rights may permit changing, adding or removing material. Others may permit access without enforcing access control. Other rules may also be imposed to organize content.

$str2 : <div class="new">Some Text Here! </div>

由于

2 个答案:

答案 0 :(得分:2)

首先,您可以使用strpos检查要分割的部分。所以在这种情况下就是

$pos = strpos($string,"<");

然后你会想要使用substr函数来相应地拆分它。

$str1 = substr($string,0,$pos); //This takes everything from the start to the position indicated

$str2 = substr($string,$pos); //This takes everything from the position to the end of the string

答案 1 :(得分:0)

所以首先找到<div的位置

$divpos = strpos(strtolower($InputString),"<div");

我使用了strtolower,以防你<DIV代替<div

然后,使用substr可以解决问题:

$str1 = trim(substr($InputString,0,$divpos));
$str2 = trim(substr($InputString,$divpos));

我使用trim删除任何不需要的空格。