我有一个文本,它是一个目录:
004 Foreword
007 Introduction
008 Chapter 1
012 Chapter 2
130 Chapter 3
274 Chapter 4
…
我需要的是找到页码,然后将每个数字包装在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
…
可以包含1到3位数字
给你:
<?
$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);
?>
因为它是一个内容表,所以我假设您要查找的数字是该行的第一个数字。
$re = '~^'D*'K'd{1,3}~m';
$subst = '<span class="page-number">$0</span>';
$result = preg_replace($re, $subst, $str);
细节:
^
表示行开始,因为使用了m修饰符
'D
非数字的任意字符
'K
从匹配结果中删除模式左侧匹配的所有内容
试试下面的代码测试
<?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;