There is the text number 2 (644) August 19, Friday, 2018

$mytext = "№2 (644) 19 январь, пятница, 2018 год"; $mytext = str_replace(',', ",\r\n", $mytext); $mytext = str_replace(')', ")\r\n", $mytext); echo nl2br($mytext); 

Now it turns out

 №2 (644) 19 августа, пятница, 2018 год 

A question such as making a line break not all commas but only the second one, well, or the last one, or from the end of the first =)

what would happen like this

 №2 (644) 19 августа, пятница, 2018 год 

    1 answer 1

    You can use regular expressions:

     $mytext = "№2 (644) 19 январь, пятница, 2018 год"; $mytext = preg_replace('~(\d{1,2}\s\pL+)|(\d{4}\s\pL{3,4})$~u', "\r\n$1$2", $mytext); echo $mytext; 

    Result:

     №2 (644) 19 январь, пятница, 2018 год 

    See Demo

    • Thank you very much, just tell me is it correct to use a regular expression for such a task as mine? - Mikhail Volkov
    • If you can get a solution in one line, then why not? Moreover, regular expressions are exactly necessary for working with substrings. - Edward