注意:这个问题与WordPress无关,而是直接与PHP相关,应该在StackOverflow 但我在下面提供了一个非常基本的答案,以帮助您实现目标。然而,请注意这个答案is not necessarily the best way 去解决你的问题,nor is it meant to be efficient.
// assuming get_the_content() equates to ↓
$content = \'<p class="1">P1 Content</p><p class="2">P2 Content</p><p class="3">P3 Content</p>\';
$classNames = [\'1\', \'2\', \'3\'];
$matches = [];
foreach( $classNames as $className ) {
$pattern = sprintf(\'\\<p\\sclass=\\"%s\\"\\>(.*?)\\<\\/p\\>\', $className);
preg_match("/{$pattern}/i", $content, $found);
$matches[] = $found;
}
var_dump($matches);
/*
array(3) {
[0]=>
array(2) {
[0]=>
string(27) "<p class="1">P1 Content</p>"
[1]=>
string(10) "P1 Content"
}
[1]=>
array(2) {
[0]=>
string(27) "<p class="2">P2 Content</p>"
[1]=>
string(10) "P2 Content"
}
[2]=>
array(2) {
[0]=>
string(27) "<p class="3">P3 Content</p>"
[1]=>
string(10) "P3 Content"
}
}
*/
更新1:
如果没有固定的已知类名列表(提前),请使用以下示例
preg_match_all
并寻找任何
<P>
标记为
class = NUMBER
.
<p class="1">Content</p>
<p class="2">Content</p>
<!-- etc.. -->
<p class="234">Content</p>
$content = \'<p class="1">P1 Content</p><p class="2">P2 Content</p><p class="3">P3 Content</p>\';
$pattern = sprintf(\'\\<p\\sclass=\\"%s\\"\\>(.*?)\\<\\/p\\>\', \'[0-9]+\');
var_dump($pattern);
preg_match_all("/{$pattern}/i", $content, $found);
var_dump($found);
/*
array(2) {
[0]=>
array(3) {
[0]=>
string(27) "<p class="1">P1 Content</p>"
[1]=>
string(27) "<p class="2">P2 Content</p>"
[2]=>
string(27) "<p class="3">P3 Content</p>"
}
[1]=>
array(3) {
[0]=>
string(10) "P1 Content"
[1]=>
string(10) "P2 Content"
[2]=>
string(10) "P3 Content"
}
}
*/
/**
* Iterate over the results (if any) and do something with the content.
*/
if ( is_array($found) && isset($found[1]) ) {
foreach( $found[1] as $content ) {
echo $content;
}
}
结果如下:
P1 Content
P2 Content
P3 Content
我建议您在类名前加前缀,例如:
<p class="myprefix-1">Content</p>
<p class="myprefix-2">Content</p>
<!-- etc.. -->
<p class="myprefix-234">Content</p>
如果是,请确保更新您的regex模式:
$pattern = sprintf(\'\\<p\\sclass=\\"myprefix-%s\\"\\>(.*?)\\<\\/p\\>\', \'[0-9]+\');