[英]How do you replace all instances of a pattern with a specific string?
Given the following...鉴于以下...
$rows = [
'Blah *-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];
... how would I replace that crappy repeating pattern of unknown length with ***
, so the result would be... ...我将如何用
***
替换未知长度的糟糕重复模式,所以结果将是...
$result = [
'Blah *** Blah',
'Blah *** Blah',
'Blah *** Blah',
];
I'm entirely unclear on how repeating patterns work in regex.我完全不清楚在正则表达式中重复模式是如何工作的。 I tried
我试过了
foreach ($rows as $r) {
echo preg_replace('/[\*\-]{3,}/', '***', $r) .'<br>';
}
and a number of other variations.和许多其他变体。 Is this an easy thing?
这是一件容易的事吗?
EDIT: I spent 30 minutes scouring stackoverflow for an answer, but found it difficult enough figuring out what question to ask.编辑:我花了 30 分钟在 stackoverflow 上寻找答案,但发现很难弄清楚要问什么问题。 I could find no relevant answer.
我找不到相关的答案。 So any help framing the question would be appreciated as well:)
因此,我们也将不胜感激提出问题的任何帮助:)
This is the way I would solve it...这就是我要解决的方法...
<?php
$rows = [
'Blah *-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];
array_walk($rows, function (&$row)
{
$row = preg_replace('/^(.*) [*-]+ (.*)$/', '$1 *** $2', $row);
});
[*-]+
is telling the regex to find any number of *
or -
characters. [*-]+
告诉正则表达式查找任意数量的*
或-
字符。
Result结果
Array
(
[0] => Blah *** Blah
[1] => Blah *** Blah
[2] => Blah *** Blah
)
You can give an array to preg_replace()
and it will perform the replacement in all the array elements.您可以给
preg_replace()
一个数组,它将在所有数组元素中执行替换。 It returns a new array of the results, it doesn't modify the array in place.它返回一个新的结果数组,它不会就地修改数组。
To match *
followed by -
, use \*-
, not [\*\-]
.要匹配
*
后跟-
,请使用\*-
,而不是[\*\-]
。 The latter matches a single character that's either *
or -
.后者匹配
*
或-
的单个字符。
$result = preg_replace('/(\*-){3,}\*/', '***', $rows);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.