【问题标题】:Wrap first and second word in span Clases PHP在 span 类 PHP 中包装第一个和第二个单词
【发布时间】:2014-08-14 08:43:07
【问题描述】:

我正在使用使用 php 的自生成导航。我需要将第一个和第二个单词包装在单独的 div 类中。例如

<li> <span>First</span> <span class="word">Second</span> Word </li>

目前我可以使用跨度类包装第一个单词

$name = preg_replace('/(?<=\>)\b(\w*)\b|^\w*\b/', '<span>$0</span>', $ni->name);

有谁知道我可以如何改变它来包装前两个单词?

【问题讨论】:

  • 输入到底是什么,应该输出什么?

标签: php regex preg-replace pcre


【解决方案1】:

您可以将单词拆分为一个数组并替换您需要的索引。

// Split on spaces.
$name = preg_split("/\s+/", $name);

// Replace the first word.
$name[0] = "<span>" . $name[0] . "</span>";

// Replace the second word.
$name[1] = "<span>" . $name[1] . "</span>";

// Re-create the string.
$name = join(" ", $name);

【讨论】:

    【解决方案2】:

    我不知道我是否理解你,但我认为你需要这个:

    $string = '<li> <span>First</span> <span class="word">Second</span> Word </li>';
    $name = preg_replace('/(<span(?:.*)>(\w*)<\/span>)/U', '<div>$2</div>', $string);
    
    echo htmlspecialchars($name);
    // <li> <div>First</div> <div>Second</div> Word </li>
    

    $string = '<li> First   Second Word </li>';
    $name = preg_replace('/<[\/]?\w*>(*SKIP)(*FAIL)|\b(\w+)\b(\s*)(\w+)\b/U', '<span>$1</span>$2<span class="word">$3</span>', $string);
    
    echo htmlspecialchars($name);
    // <li> <span>First</span> <span class="word">Second</span> Word </li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2017-02-26
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多