PHP Preg-replace - Identify only dashes, spaces and breaks
Good morning, I have a string in which there are breaks represented as <p>----</p>
. The number of dash is often different. Sometimes there are 4, sometimes 5, etc.
Something like this:
Lorem ipsum
<p>------</p>
Lorem Ipsum
<p>
I would like to write a php preg_replace command to make them all uniform and identical.
This is what I developed, but it doesn't work. Where is the error?
{-code-3}
Moreover there is something more precise rather than {-code-4}
to match only spaces and dashes.
EDIT 1: Thanks to the team in the answer section, I correct the function like this:
{-code-5}
This works fine as long as long the text doesn't have a break between the last dash and {-code-6}
. How can I identify the dashed, spaces and also capture the {-code-7}
?
Example:
<p>----- {-code-7}{-code-6}
Answer
Answer
Answer
Answer
Answer
Solution:
You don't really need the 3 capture groups. You can match zero or more horizontal whitspace chars using {{-code-3}code{-code-3}1}
and replace that with the fixed replacement of {{-code-3}code{-code-3}2}
Example, where as in your code there is always a {-code-3}
at the start and end:
$item = <<<DATA
Lorem ipsum
<p>{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}</p>
Lorem Ipsum
<p>{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}</p>
Lorem Ipsum
<p>{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3}{-code-3} {-code-3}{-code-3}{-code-3}{-code-3}{-code-3}</p>
DATA;
$search = "~<p>{-code-3}{{-code-3}code{-code-3}1}{-code-3}</p>~";
$replace = "{{-code-3}code{-code-3}2}";
$item = preg_replace($search, $replace, $item);
echo $item;
Output
Lorem ipsum
{{-code-3}code{-code-3}2}
Lorem Ipsum
{{-code-3}code{-code-3}2}
Lorem Ipsum
{{-code-3}code{-code-3}2}
Answer
Answer
Answer
Answer
Answer
Answer
Answer
Solution:
You may try finding the pattern and then replace with however many dashes you want, e.g.
{-code-2}
:
$input = "Lorem ipsum \n<p>------</p>\nLorem Ipsum \n<p>Answer
------</p>\nLorem Ipsum\n<p>Answer
----</p>";
$output = preg_replace("/<p>\s*-{1,}\s*<\/p>/", "<p>-----</p>", $input);
echo $output;
This prints:
Lorem ipsum
<p>-----</p>
Lorem Ipsum
<p>-----</p>
Lorem Ipsum
<p>-----</p>