如何用\ n替换句子中的第三个空格

时间:2018-07-11 10:14:24

标签: php string replace newline

如何在接下来的句子中用"\n"替换第三个空格和连续的空格?

  

请在会议结束后提出您的问题。

4 个答案:

答案 0 :(得分:0)

尝试一下,应该可以工作

<?php

$sentence = 'Some really long sentence without any kind of sense';

$se = explode(' ', $sentence);
$s = '';

$i = 0;
while ($i < count($se)) {
    $i++;
    $s .= $se[$i-1];
    if ($i !== count($se)) {
        if ($i%3 == 0) {
            $s .= '\n';
        } else {
            $s .= ' ';
        }
    }
}

echo $s;

答案 1 :(得分:0)

<?php
$str    = 'Please ask your questions after the session is finish';
$words  = explode(' ', $str);
$result = '';
foreach($words as $k => $word)
    $result .= $word . ($k<2 ? ' ' : "\n");
var_dump($result);

输出:

string(54) "Please ask your
questions
after
the
session
is
finish
"

答案 2 :(得分:0)

这里的Regex是一个很好的选择,因为它不需要在输入字符串上进行任何“斩波”来运行迭代操作,并且一旦将头\G (continue anchor)包裹在“魔术”上,它就非常简单。如果这是我的项目,我将使用正则表达式而不是非正则表达式方法,因为它是一种直接而简洁的方法,而给定示例输入字符串,最终用户完全不会注意到任何性能损失。

代码:(Demo

$string = "Please ask your questions after the session is finished.";
echo preg_replace('~(?:^\S+ \S+ |\G(?!^))\S+\K ~', "\n", $string);

输出:

Please ask your
questions
after
the
session
is
finished.

Pattern Demo

~          #pattern delimiter
(?:        #start of non-capturing group
  ^        #match start of string
  \S+ \S+  #match one or more visible characters, a literal space, one or more visible characters, a literal space
  |        #or
  \G(?!^)  #continue from last match, but not the start of the string
)          #end of non-capturing group
\S+        #match one or more visible characters
\K         #restart the fullstring match (ignore previously matched characters)
           #match a literal space  (the only replaced character)
~          #pattern delimiter

*如果输入字符串中没有可替换的合格空格,则输入字符串将保持不变,并且不会生成任何错误/警告/通知。

答案 3 :(得分:0)

用换行符Option Explicit Sub DeleteVendorOnly() Dim tbl As ListObject Dim colIndex As Integer Dim rngToDelete As Range Set tbl = Sheets("Sheet1").ListObjects("Table1") ' Change to your sheet name colIndex = tbl.ListColumns("Vendor Item?").Index tbl.Range.AutoFilter Field:=colIndex, Criteria1:="Yes" On Error Resume Next Set rngToDelete = tbl.DataBodyRange.SpecialCells(xlCellTypeVisible) On Error GoTo 0 If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete End If End Sub 替换第三个空格和后续空格的一种方法是获取第三个出现位置的字符串中的偏移量,并使用该偏移量来替换字符。

要获取偏移量,可以使用preg_match_all,使用\n来匹配一个或多个水平空白字符,并使用\h+标志。 (来自文档)如果传递了此标志,则对于每次发生的匹配,还将返回附加字符串偏移量。

要替换字符,您可以使用substr_replace

对于PREG_OFFSET_CAPTURE参数,请使用start;对于length参数,请使用$matches[0][2][1]。索引0是返回的数组,索引2是第三个匹配项,索引0包含匹配项,索引1包含偏移量。

$matches[0][2][0]

将导致:

$str = "Please ask your questions after the session is finished.";
preg_match_all('/\h+/', $str,$matches, PREG_OFFSET_CAPTURE);
$str = substr_replace($str, "\n", $matches[0][2][1], strlen($matches[0][2][0]));
echo $str;

Demo