0

i have tried many solutions but couldn't figure out the issue. I have a object with some properties. This is my object

object(room)[16]
 public 'id' => string '144323'
 public 'jobId' => string '115141'
 public 'name' => string 'Room 1'
 public 'description' => string 'This is\r\nMy test'
 .....
 .....

I am trying to remove \r\n from description and here is my code for that

$noSymbols = preg_replace('~[\r\n]+~', ' ', $room->description)

Weird thing is if i change $room->description with This is\r\nMy test then i get my output as This is My test but with php variable, it doesn't work and giving me output as This is\r\nMy test.

Thanks!

Harpreet Singh
  • 999
  • 9
  • 19

1 Answers1

2

You can use preg_quote() to escape the regex special characters.

A line in the preg_quote API doc says:

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #

Since you have the \ in your regex which is a regex special character, you preg_quote() them and then match them like below:

<?php

$o = new stdclass();
$o->description = 'This is my\r\ntest';
echo preg_replace('/['.preg_quote('\r\n').']+/',' ',$o->description);
nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • @Harpreet The function call is not actually necessary, the fix can be done without. https://3v4l.org/AaXqK – mickmackusa Jun 25 '20 at 06:56
  • @mickmackusa It's ok to use the function as well, no harm. – nice_dev Jun 25 '20 at 06:59
  • @mickmackusa I actually meant it just for it's usage and I have amended it since it was ambiguous in terms of truth(as English is not my first language). Also, preg_quote() is anyways better if OP wants to add some more characters for the replacement, else he will need to pay attention to whether the new chars have meta characters or not if done manually. – nice_dev Jun 25 '20 at 07:16