php preg_replace长字符串的一部分

时间:2013-09-03 23:51:19

标签: php regex

我有一个包含这些长描述的数据库,我需要弄清楚如何从描述中提取位置代码。我正在使用preg_replace()来匹配它,就像这个示例条目一样。

$string = "Honda 1982 VF750C Magna right-side radiator trim panel. Good, damage-free condition. Needs cut and polished. Cheap, fast shipping! 011425 H6 <img src=\">http://www.roofis27.com/motorcycle/10_01_14/030.JPG\"> n=\">";
$pattern = '(\d\d\d\d\d\d\s\D\d)'; 
$replace = '$1';
echo 'Replaced String: ' . preg_replace($pattern, $replace, $string) . '<br>';
echo '<br>';
echo 'Original String: ' . $string;

我需要做的是删除{strong>但 011425 H6$string的所有内容。我无法弄清楚如何摆脱其余的字符串。我可以匹配模式,但是我使用什么正则表达式来删除其余的字符串?更少删除011425 H6之前和之后的所有内容。任何帮助将不胜感激,并提前感谢:)

1 个答案:

答案 0 :(得分:0)

只是一个小修改,然后它应该工作:

<?php

$string = "Honda 1982 VF750C Magna right-side radiator trim panel. Good, damage-free condition. Needs cut and polished. Cheap, fast shipping! 011425 H6 <img src=\">http://www.roofis27.com/motorcycle/10_01_14/030.JPG\"> n=\">";
$pattern = '/^.*\b(\d\d\d\d\d\d\s\D\d)\b.*$/';
$replace = '$1';
echo 'Replaced String: ' . preg_replace($pattern, $replace, $string) . '<br>';
echo '<br>';
echo 'Original String: ' . $string;