-2
$str = "for(var i = 0; i < aLinks.length; i++) {"; 

preg_replace( "!\s+!", "", $str  );

output: for(vari=0;i

My desired output is

for(var i=0;iaLinks.length;i++){

if I remove the arrow like this $str = "for(var i = 0; i (no arrow here) aLinks.length; i++) {"; then I get the desired output.

Why does the back arrow break the regex?

What I want the regex to do is remove all tabs line breaks and spaces and nothing else. the strings may have operators like < or > etc and I want these to be ignored.

5
  • my first guess is to add slashes? ie \< or \> ??? its a bit annoying though to have to do that first surely regex can do what i want in 1 line. Jul 31, 2021 at 11:29
  • 2
    Are you sure the problem is with preg_replace()? This seems to work fine: 3v4l.org/TBnOe (output is: for(vari=0;i<aLinks.length;i++){) Jul 31, 2021 at 11:30
  • 4
    Do you output on CLI or in your browser? Did you take a look at the source of the page, most likely your browser interprets < as the start of an HTML element and doesn't display from that char on
    – brombeer
    Jul 31, 2021 at 11:32
  • omg how embarrassing!!! yes i'm viewing in the browser. Should i delete this or leave it here, possibly there are others as thick as me lol Jul 31, 2021 at 11:33
  • It's a good question, perhaps you'd like to answer it yourself @FeelsUnique? You can edit your title as well and add "in the browser" to make it reproducible. Jul 31, 2021 at 19:51

1 Answer 1

0

This was a stupid school boy error. I was viewing the output in a browser so it was interpreting the "<" as a tag and everything after that was invisible. Simply viewing the source in the browser showed it was actually working exactly as expected.

Not the answer you're looking for? Browse other questions tagged or ask your own question.