0

在表回显期间,我将如何使用正则表达式替换所有数字?

我希望使用正则表达式将所有数字替换为包含数字的跨度,以便我可以更改他们的类。

我无法在回显期间添加跨度,因为表格是从文本文件中提取并在屏幕上回显的,它必须替换已经从文本文件中提取的数字。

PHP:

//set file
$filename='schedule.txt';
//open
$handler=fopen('schedule.txt','r');
//read through file
$file=fread($handler,filesize($filename));
$lines=explode("\r\n",$file);
etc....
4

2 回答 2

2

您可以执行以下操作:

$changed_lines = preg_replace('#(\d+)#', '<span class="bla">$1</span>', $lines);
于 2012-04-23T17:05:20.117 回答
1

使用循环遍历行foreach(),然后使用替换preg_replace()

foreach ($lines as $line){

    $line = preg_replace('!\d+!', '<span>$0</span>', $line);
    echo "$line\r\n";
}

使用此输入:

woo yay 19 foo
foo 12 bar

我得到这个输出:

woo yay <span>19</span> foo
foo <span>12</span> bar

如果这不是您要找的,请用具体示例更新您的问题。

于 2012-04-23T17:07:45.230 回答