使用 PHP -explode \ preg_split 正则表达式在 WordPress \ WooCommerce 中按段落拆分产品描述,获取不需要的字符

问题描述 投票:0回答:1

我正在尝试向我们的网站添加一项功能,如果该产品没有手动添加简短描述,则可以使用详细描述中的前 2 段自动填充产品简短描述。

我的功能总体正常,但我们发现我们的一些产品文本以标题开头

( <h2> up to <h5> )

我的函数检查第一段是否不以“”开头

我使用了

$headerex = explode('</h2>', $long_description);
,效果很好,但仅用于在标签后分割字符串。因此,如果我们有以 H5 开头的文本,例如,我将得不到任何回复。

发现爆炸不适用于正则表达式(en?),所以我尝试使用 preg_split 代替。

我不熟悉正则表达式的所有细微差别以及如何正确使用它,而且我对 PHP 还很陌生。

        $regexx = '</h[0-9]>';
        $headerex = preg_split($regexx, $long_description);

使用这段代码时,我几乎像我想要的那样分割了字符串。 问题是标题部分以打印“<" to the page after the header text. When returning the second part that comes after the [ x = digit ] It starts with an ">”结尾。

我缺少正则表达式或 preg_split。 我也尝试过

$regexx = '</h\d>
。他们不适合我:(

  if ( ! $short_description ) {
    $short_descpars = explode('</p>', $long_description);
    $short_descpar = $short_descpars[0];
    if (strpos($short_descpar, '<h', 0) === false ){
        $short_description = $short_descpar . " " . $short_descpars[1];
    } else {
//      $headerex = explode('</h2>', $long_description);
        $regexx = '</h[0-9]>';
        $headerex = preg_split($regexx, $long_description);
        $headerex2 = $headerex[1];
        $headerexx = explode('</p>', $headerex2);
        $short_description = $headerexx[0] . " " . $headerexx[1];
    }
        
?>
        <div class="product_short_desc">
        <p class="short_desc_header">
        <?php echo $short_description; // WPCS: XSS ok. ?> </p>
        <p class="long_desc_link">
        <a href="#prod_full_desc"> קרא עוד על המוצר</a>
        </p>
        </div>
<?php
    }
    

停用的代码

  $headerex = explode('</h2>', $long_description);
有效,但仅适用于 h2,我不想为每个标题大小复制它。 例如,以 h5 开头的文本 - 只是错过了逻辑并且在前端没有显示任何内容。

使用

</h[0-9]>
作为带有 preg_split 的正则表达式,输出文本显示如下: 逃跑者< tag

php wordpress woocommerce preg-split
1个回答
0
投票

您可以将 preg_split 与正则表达式模式 // 结合使用,通过任何标头标签(从

)分割字符串。然后,它检查第一个段是否以标头标记开头。如果它确实以标头标记开头,它将跳过该段并采用接下来的两个段作为简短描述。如果没有,则将前两段作为简短描述。请看一下:

function get_short_description($long_description) {
    // Split the long description by any header tag
    $headerex = preg_split('/<\/?h[1-6]>/', $long_description, 3, PREG_SPLIT_DELIM_CAPTURE);
    
    // Check if the first segment is a header tag
    if (strpos($headerex[0], '<h') !== 0) {
        // If not, take the first two segments as the short description
        return implode('', array_slice($headerex, 0, 2));
    } else {
        // If it is, skip the header and take the next two segments
        return implode('', array_slice($headerex, 1, 2));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.