使用 php 将前两个单词换行

Using php to wrap first two words in a span

我想弄清楚如何使用 php 将字符串的前两个单词包装在一个跨度中,它类似于:

Wrap first and second word in span Clases PHP

但是我一次需要两个词。例如:

输入字符串:

Apartment 1 8 Share

预期输出:

<span>Apartment 1</span> 8 Share

试试这个最简单的。

Regex code demo

正则表达式: ^([^\h]+\s[^\h]+)

如果白色 space 一开始就出现,我们可以选择使用 ^(\s*[^\h]+\s[^\h]+)\s* 是零个以上的白色 space。

1. ^ start of string.

2. [^\h] match except horizontal white space.

3. \s This will match space.

4. [^\h]+ match all except horizontal white space.

5. () will capture first captured group in </code></p> </blockquote> <p>我们可以选择使用 <code>\s 而不是 \h

Try this code snippet here

<?php
ini_set('display_errors', 1);

$string="Apartment 1 8 Share";
echo preg_replace("/^([^\h]+\s[^\h]+)/", "<span></span>", $string);