我想学习如何在不使用实际的preg_split函数的情况下,使用一组和preg_split函数做同样事情的php代码。以此为例
<?php
$string = '<p>i am a sentence <span id="blah"> im content inside of the span </span> im another sentence <span id="anId">i m another span content</span> im the last sentence in this p tag <span id="last">im the third span tag in this p tag<span></p>';
if ( preg_match_all("/<span[^>]*>/", $string, $temporaryArray) ) {
foreach ($temporaryArray as $values) {
$theArrayWithoutUsingPregSplit[$strpos] = $values;
}
}
?>然而,这并不起作用,因为preg_match_all只计算它匹配的次数,而没有获得实际的字符串。但是这个页面上的人http://php.net/manual/en/function.preg-split.php#118326能够做到这一点。有人能帮帮忙吗。
此外,我希望使用strpos()函数作为每个数组元素的键,这样我就可以看到$string变量中的值的位置,在我给出的示例中,变量没有值。
im尝试从字符串变量获得的最终输出是
array (
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] i am a sentence
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im content inside of the span
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im another sentence
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] i m another span content
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im the last sentence in this p tag
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im the third span tag in this p tag
)我不认为在这个场景中使用preg_split是最好的方法,因为我不能使用数组键来表示值的strpos。
很抱歉写了这么多,我试着让这个问题变得尽可能容易理解,否则人们可能会反对它,如果你有任何问题可以随时提出。
发布于 2018-01-27 05:40:50
使用DOMDocument:
$string = '<p>i am a sentence <span id="blah"> im content inside of the span </span> im another sentence <span id="anId">i m another span content</span> im the last sentence in this p tag <span id="last">im the third span tag in this p tag<span></p>';
$dom = new DOMDocument;
$dom->loadHTML($string, LIBXML_HTML_NOIMPLIED);
$xp = new DOMXPath($dom);
foreach($xp->query('//text()') as $textNode) {
echo trim($textNode->nodeValue), PHP_EOL;
}这种方法包括使用带有简单查询//text() ( DOM树中任意位置的文本节点)的XPath查询语言询问每个文本节点。
发布于 2018-01-27 05:42:01
要获取<span>和</span>之间的文本,您需要更改正则表达式以匹配它们,并在两者之间使用捕获组。
$temporaryArray是一个二维数组;元素0包含整个regexp的匹配项,元素N包含第N个捕获组的匹配项。所以你想要的字符串在$temporaryArray[1]中。如果您还需要这些位置,请使用PREG_OFFSET_CAPTURE选项。使用此选项,每个匹配项都是一个数组[ "string", strpos ]。
if ( preg_match_all('#<span[^>]*>(.*?)</span>#', $string, $temporaryArray, PREG_OFFSET_CAPTURE) ) {
$theArrayWithoutUsingPregSplit = array();
foreach($temporaryArray[1] as $match) {
$theArrayWithoutUsingPregSplit[$match[1]] = $match[0];
}
}发布于 2018-01-28 02:55:21
很抱歉我可能给您带来了麻烦,我想不使用preg_split()函数的原因是因为我认为preg_split()不能返回它返回的字符串的$Array = preg_split('/<[^>]*>/', $string, 0, PREG_SPLIT_OFFSET_CAPTURE);,但一直以来它只是像下面这样的strpos来获得我想要的东西。我只希望能够从字符串中获取strpos和字符串。我喜欢这个网站有这样一个乐于助人的社区,我感谢你们的帮助,我非常感谢。
https://stackoverflow.com/questions/48469757
复制相似问题