[英]How do you replace all instances of a pattern with a specific string?
鉴于以下...
$rows = [
'Blah *-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];
...我将如何用***
替换未知长度的糟糕重复模式,所以结果将是...
$result = [
'Blah *** Blah',
'Blah *** Blah',
'Blah *** Blah',
];
我完全不清楚在正则表达式中重复模式是如何工作的。 我试过了
foreach ($rows as $r) {
echo preg_replace('/[\*\-]{3,}/', '***', $r) .'<br>';
}
和许多其他变体。 这是一件容易的事吗?
编辑:我花了 30 分钟在 stackoverflow 上寻找答案,但发现很难弄清楚要问什么问题。 我找不到相关的答案。 因此,我们也将不胜感激提出问题的任何帮助:)
这就是我要解决的方法...
<?php
$rows = [
'Blah *-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];
array_walk($rows, function (&$row)
{
$row = preg_replace('/^(.*) [*-]+ (.*)$/', '$1 *** $2', $row);
});
[*-]+
告诉正则表达式查找任意数量的*
或-
字符。
结果
Array
(
[0] => Blah *** Blah
[1] => Blah *** Blah
[2] => Blah *** Blah
)
您可以给preg_replace()
一个数组,它将在所有数组元素中执行替换。 它返回一个新的结果数组,它不会就地修改数组。
要匹配*
后跟-
,请使用\*-
,而不是[\*\-]
。 后者匹配*
或-
的单个字符。
$result = preg_replace('/(\*-){3,}\*/', '***', $rows);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.