我有一个字符串
&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&
我必须删除这个部分& 185601651932 | mobile | 3 | 120 | 1& (以放大器开头,以放大器结尾)只知道第一个数字直到垂直线(185601651932)
所以结果我会有
&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5&
我怎么能用PHP preg_replace函数做到这一点。行(|)分隔值的数量总是相同的,但仍然,id喜欢具有灵活的模式,而不是取决于&和/或之间的行数。登录。
感谢。
P.S。此外,我会很高兴链接到一个良好的简单书面资源相关的PHP中的正则表达式。谷歌中有很多这些:)但也许你碰巧有一个非常好的链接
答案 0 :(得分:1)
preg_replace("/&185601651932\\|[^&]+&/", ...)
广义,
$i = 185601651932;
preg_replace("/&$i\\|[^&]+&/", ...);
答案 1 :(得分:0)
如果您想要真正的灵活性,请使用preg_replace_callback。 http://php.net/manual/en/function.preg-replace-callback.php
答案 2 :(得分:0)
重要提示:请勿忘记使用preg_quote()
转义您的号码:
$string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$number = 185601651932;
if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) {
// $matches[0] contains the captured string
}
答案 3 :(得分:0)
在我看来,你应该使用另一种数据结构而不是字符串来操作这些数据。 我希望这个数据像
这样的结构Array(
[id] => Array(
[field_1] => value_1
[field_2] => value_2
)
)
你可以通过这样的方式将大块的弦按摩成这样的结构:
$data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$remove_num = '185601651932';
/* Enter a descriptive name for each of the numbers here
- these will be field names in the data structure */
$field_names = array(
'number',
'phone_type',
'some_num1',
'some_num2',
'some_num3'
);
/* split the string into its parts, and place them into the $data array */
$data = array();
$tmp = explode('&', trim($data_str, '&'));
foreach($tmp as $record) {
$fields = explode('|', trim($record, '|'));
$data[$fields[0]] = array_combine($field_names, $fields);
}
echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n";
/* Now to remove our number */
unset($data[$remove_num]);
echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";