Leanne Seawright Leanne Seawright -4 years ago 79
PHP Question

Using php to wrap first two words in a span

I'm trying to figure out how to use php to wrap the first two words of a string in a span, it's similar to this:

Wrap first and second word in span Clases PHP

But I need two words in the one span. Eg:

Input string:

Apartment 1 8 Share


Expected output:

<span>Apartment 1</span> 8 Share

Answer Source

Try this simplest one.

Regex code demo

Regex: ^([^\h]+\s[^\h]+)

Optionally we can use ^(\s*[^\h]+\s[^\h]+) if white space comes at very starting.\s* is for zero more white spaces.

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 $1

Optionally we can use \s instead of \h.

Try this code snippet here

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

$string="Apartment 1 8 Share";
echo preg_replace("/^([^\h]+\s[^\h]+)/", "<span>$1</span>", $string);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download