0

unfortunately, I have to deal with faulty HTML entities in a text, for example

&middot,

instead of the correct entity with the ending semicolon.

I tried

$pattern = "/^&[a-zA-Z]+?,/";
$replace =  "/^&[a-zA-Z]+?;/";
$detailtext = preg_replace($pattern,$replace, $detailtext);

but it doesn't work... This is driving me nuts, I'm new to regular expressions and any help would be greatly appreciated!

Example for $detailtext:

$detailtext = "Unterputz-Einsätze<br>mit Federklemmen (Verbindungsklemmen nach VDE 0632). <br>Die Einsätze können wahlweise mit Standard- oder Flächenabdeckung <br>bestückt werden.<br>Wippschalter<br>10 AX 250 V&sim,<br>Ausführung: Universalschalter (Aus-Wechsel)<br>"
6
  • 2
    You have # in your pattern and &middot, does not contain the hash. So, it is not that surprising. Commented May 6, 2016 at 9:27
  • show the $detailtext value Commented May 6, 2016 at 9:30
  • tried it without the #. added it because of an answer i read on SO. Does not work without it either Commented May 6, 2016 at 9:30
  • 1
    Are they always at the beginning of the string? If not, remove ^. See '~&[a-z]+[,;]~i. Commented May 6, 2016 at 9:31
  • they are not at the beginning of the string. removed the ^, but now i get &[a-zA-Z]+?; instead of the correct entity Commented May 6, 2016 at 9:37

2 Answers 2

2

You should try this:

$pattern ="/(&[a-zA-Z]+),/"
$replace ="$1;";
$detailtext = preg_replace($pattern,$replace, $detailtext);

The parenthesis will capture entities that are followed by "," and you can retrieve them with "$n", n being the capture group number. So replace with "$1" followed with ending semicolon.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks a lot for the short but very clear answer.
0

Try this:

$str = preg_replace("/(\&.*)(\,)/", "$1;", $str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.