Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace: how to?

If there is one thing I can't understand ( or learn ), then that's preg_replace syntax. I need help removing all possible symbols ( space, tab, new line, etc. ) between > and <.

Meaning, I have such XML:

<?xml version=\"1.0\" encoding=\"UTF-8\"?><bl>  <snd>BANK</snd>    <rcv>ME</rcv>  <intid>773264</intid> <date>17072012</date></bl>

I need it to look:

<?xml version=\"1.0\" encoding=\"UTF-8\"?><bl><snd>BANK</snd><rcv>ME</rcv><intid>773264</intid><date>17072012</date></bl>

So far I came up with this:

$this -> data = preg_replace('\>(.*?)<\', '><', $data);

But it doesn't even come close to what I need. A solution would be appreciated.

like image 920
Peon Avatar asked Jul 17 '12 15:07

Peon


2 Answers

You're close, you just need delimiters and to restrict your search for space characters:

preg_replace('#>\s+<#', '><', $data);

Where # is the delimiter character, and \s is shorthand for any space characters.

You can see it working in this example.

like image 66
nickb Avatar answered Oct 07 '22 19:10

nickb


For removing spaces:

preg_replace('/\s\s+/', ' ', $data);

For removing new lines:

$string = preg_replace('/\r\n/', "", $data);
like image 26
Indian Avatar answered Oct 07 '22 20:10

Indian