I have a text which is a table of contents:
004 Foreword
007 Introduction
008 Chapter 1
012 Chapter 2
130 Chapter 3
274 Chapter 4
…
What I need, is to find the page numbers and then wrap each number in a span
:
<span class="page-number">004</span> Foreword
<span class="page-number">007</span> Introduction
<span class="page-number">008</span> Chapter 1
<span class="page-number">012</span> Chapter 2
<span class="page-number">130</span> Chapter 3
<span class="page-number">274</span> Chapter 4
…
The numbers could contain of 1 to 3 digits.
Since it is a table of content, I assume that the number you are looking for is the first number of the line.
$re = '~^\D*\K\d{1,3}~m';
$subst = '<span class="page-number">$0</span>';
$result = preg_replace($re, $subst, $str);
details:
^
means the start of the line, since the m modifier is used
\D
any character that is not a digit
\K
removes all that have been matched by the left of the pattern from the match result
Here you go:
<?
$text = <<<TEXT
004 Foreword
007 Introduction
008 Chapter 1
012 Chapter 2
130 Chapter 3
274 Chapter 4
TEXT;
echo preg_replace('/^(\d+)/m', '<span class="page-number">$1</span>', $text);
?>
Try this code test here
<?php
$text = 'TEXT
004 Foreword
007 Introduction
008 Chapter 1
012 Chapter 2
130 Chapter 3
274 Chapter 4
';
$text = preg_replace('/[\d]{3}/m', '<span class="page-number">$0</span>', $text);
echo $text;