I would like to replace a space after a number with hard-space " " only in p tags.
I wrote this code:
$pattern = "/<p>[0-9] </p>/";
return preg_replace($pattern, "$1 ", $text);
But it does nothing, why? Can you please help?
Example:
Input : "My 90 days work."
Output: "My 90 days work."
Thank you a lot.
2
Answers
Try this:
Matching html with a regex is not advisable, but if there can be no angle brackets in between, you might get away with a single pattern using the
G
anchor:Explanation
(?:
Non capture group<p>(?=[^<>]*</p>)
Match<p>
and assert a closing</p>
without angle brackets in between|
OrG(?!^)
Assert the current position at the end of the previous match, but not at the start of the string)
Close the non capture group[^d<>]*
Match optional chars other than<
or>
or a digitd+
Match 1+ digitsK
Forget what is matched so farh
Match a single horizontal whitespace charSee a regex demo and a PHP demo.
Output
Or using DOMDocument to find the paragraphs, and do the replacement after matching a digit and a horizontal whitespace char:
Output