在PHP中没有空格的字符串中查找单词

时间:2012-09-20 15:03:22

标签: php xml string parsing find

我用PHP解析XML文件。我的问题是我有一个包含多行的动态字符串,每行都没有空格字符,我想在该字符串上找到一个单词。字符串的长度是动态的,因此每次都会改变。

由于字符串长度是动态的,我不能使用像$c = substr($string, 0, -1)这样的东西,或者因为字符串中没有空格而无法使用$i=stripos($story," word");之类的内容。

示例字符串是4行,我想在</a>之前的第二行检测到ARC.docx这个词:

<![CDATA[
In <a href='/home/Apps/ARCMeeting'>ARCMeeting</a>, You edited the file <a href='https://dropbox.com/get/Apps/ARCMeeting/ARC.docx?w=d3' title='&#47;Apps&#47;ARCMeeting&#47;ARC.docx'>ARC.docx</a>.
<br/>
]]>

我的目标是在</a>之前的第二行将ARC.docx添加到邮件正文

$message='X File has been edited!';

所以我可以打印

$message='ARC.docx File has been edited!';

如何检测上述字符串.......>exampleword</a>.之间的单词?

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以尝试preg_match功能。

在您的情况下,它看起来像:

$subject = "In <a href='/home/Apps/ARCMeeting'>ARCMeeting</a>, You edited the file <a href='https://dropbox.com/get/Apps/ARCMeeting/ARC.docx?w=d3' title='&#47;Apps&#47;ARCMeeting&#47;ARC.docx'>ARC.docx</a>"

preg_match("/title=(.*)>(.*)<\/a>/U", $subject, $matches);

echo $matches[2]; // $matches[2] will contain `ARC.docx`

答案 1 :(得分:2)

使用DOM parser,例如PHP中内置的。{/ p>

$doc = new DOMDocument();

$html_string = <<<EOD
 <![CDATA[
 In <a href='/home/Apps/ARCMeeting'>ARCMeeting</a>, You edited the file <a href='https://dropbox.com/get/Apps/ARCMeeting/ARC.docx?w=d3' title='&#47;Apps&#47;ARCMeeting&#47;ARC.docx'>ARC.docx</a>.
 <br/>
 ]]>
EOD;

@$doc->loadHTML($html_string);

$urls = $doc->getElementsByTagName('a');

foreach ($urls as $url) {
 echo $url->nodeValue;
}
  

ARC.docx