1

I am trying to remove a piece of string that begins between Int. and newline.

$string = preg_replace('/Int.[\s\S]+?\n/', '', $string);

Here is the source string:

My address
Int. blabla
blabla blabla

Is that possible?

1
  • please always include the expected result into the question body Commented Feb 26, 2016 at 8:49

2 Answers 2

2

You can use the following solution:

$s = "My address\nInt. blabla\nblabla blabla";
$s = preg_replace('~Int\.\h*([^\r\n]+)[\r\n]*~', '', $s);
echo $s; // => My address\nblabla blabla

See IDEONE demo

The regex will match Int., then zero or more spaces (\h*, just to left-trim the result) and then will capture into Group 1 one or more characters other than line feed and carriage return symbols (([^\r\n]+))

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

9 Comments

Do you ever sleep, Wiktor?
@Jan usleep maybe :) :) :)
I slept some 6 hours - enough :) I will sleep it off on Saturday and Sunday.
Stdout: blablabla? Shouldn't be there "My address" as well?
@AMartinNo1: begins between "Int." and newline. The negated character class [^\r\n] with + quantifier matches 1+ characters other than newline symbols.
|
1

To remove your string, just use the following code:

$string = "My address\nInt. blabla\nblabla blabla";
$regex = '~       # delimiter
          ^Int\.  # Looks for Int. at the beginning of a line
          .*      # everything else except a newline
          ~xm';   # free spacing mode and multiline
$replacement = '';
$string = preg_replace($regex, $replacement, $string);

You need the modifiers x to allow the comments and m to allow the caret (^) to match at any line. If you want to remove the whole line (including a newline character, that is), change the regex to:

$regex = '~^Int\..*\R~m';

See a demo on ideone.com.

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.