PHP str_replace 有偏移量

PHP str_replace with an offset

我有以下输出:

Item
Length : 130
Depth : 25
Total Area (sq cm): 3250
Wood Finish: Beech
Etc: etc

我想从字符串中删除总面积 (sq cm): 和它后面的 4 位数字,目前我正在尝试像这样使用 str_replace:

$tidy_str = str_replace( $totalarea, "", $tidy_str);

这是正确使用的函数吗?如果是这样,我如何在该文本后包含 4 个随机数字?另请注意,这不是设置输出,因此字符串将在此范围内改变位置。

试试这个:

  preg_replace('/(Total Area \(sq cm\): )([0-9\.,]*)/' , '', $tidy_str);

这样就可以了。

$exp = '/\(sq cm\): \d+/';


echo preg_replace($exp, '', $array);

您可以在 http://www.phpliveregex.com/

练习 php 正则表达式
<?php

$str = '
Item
Length : 130
Depth : 25
Total Area (sq cm): 3250
Wood Finish: Beech
Etc: etc
';

echo preg_replace("/Total Area \(sq cm\): [0-9]*\n/", "", $str);
Item
Length : 130
Depth : 25
Wood Finish: Beech
Etc: etc

您正在寻找substr_replace

$strToSearch = "Total Area (sq cm):";
$totalAreaIndex = strpos($tidy_str, $strToSearch);
echo substr_replace($tidy_str, '', $totalAreaIndex, strlen($strToSearch) + 5); // 5 = space plus 4 numbers.

如果你也想删除换行符,你应该检查它是\n还是\r\n。 \n 加一,\r\n 加二到偏移量。 IE。 strlen($strToSearch) + 7