我有一个输入字符串:
$subject = "This punctuation! And this one. Does n't space that one."
我也有一个数组,其中包含我要执行的替换的异常,当前只有一个成员:
$exceptions = array(
0 => "n't"
);
我想实现的复杂解决方案的原因是,此阵列将来会扩展,并可能包含数百个成员。
我想在单词边界处插入空格(重复的空格将在以后删除)。但是,应忽略某些边界。例如,上述句子中的感叹号和句号应包含空格,但撇号不应包含空格。一旦从的最终结果中删除了重复的空格trim(preg_replace('/\s+/', ' ', $subject));
,它应该看起来像这样:
"This punctuation ! And this one . Does n't space that one ."
我正在研究以下解决方案:
使用preg_match('\b', $subject, $offsets, 'PREG_OFFSET_CAPTURE');
收集这里的空白可以插入索引数组。
遍历$offsets
数组。
$subject
在当前偏移量之前从空白处拆分,直到下一个空白处或行尾。$exceptions
数组中。到目前为止,我有以下代码:
$subject="This punctuation! And this one. Does n't space that one.";
$pattern = '/\b/';
preg_match($pattern, $subject, $offsets, PREG_OFFSET_CAPTURE );
if(COUNT($offsets)) {
$indexes = array();
for($i=0;$i<COUNT($offsets);$i++) {
$offsets[$i];
$substring = '?';
// Replace $substring with substring from after whitespace prior to $offsets[$i] until next whitespace...
if(!array_search($substring, $exceptions)) {
$indexes[] = $offsets[$i];
}
}
// Insert whitespace character at each offset stored in $indexes...
}
我找不到合适的方法来创建$substring
变量以完成上述示例。
$res = preg_replace("/(?:n't|ALL EXCEPTIONS PIPE SEPARATED)(*SKIP)(*F)|(?!^)(?<!\h)\b(?!\h)/", " ", $subject);
echo $res;
输出:
This punctuation ! And this one . Doesn't space that one .
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句