0

I have a text area, I need parse text when form is submitted.

For example I need to get first string from this text area, get it and left whole text as is. I don't want to use nl2br function and then use pattern with <br />. Can I just parse \n chars and if so how? I can't do it in my php code, but I can in regex tester link to example is below.

http://regex101.com/r/mK7hF2

this is my code that doesn't work:

preg_match('/(.+)\n\n/', $_POST['text'],$title);

$title = $title[0];

echo $title;

it returns nothing. Help me to change this, thanks.

EDIT

enter image description here

Dima Deplov
  • 3,538
  • 6
  • 41
  • 73

3 Answers3

3

You don't need regular expressions for this, use strtok:

$title = strtok( $_POST['text'], "\n" );

Edit

Ok, try then with \R to match any type of line endings '/(.+)\R/'

Danijel
  • 11,490
  • 4
  • 32
  • 51
  • at least it work =), but I'm looking for regex solution. If I didn't found another solution for exactly my question I will mark this as right answer. – Dima Deplov Jun 24 '14 at 15:41
  • that's made it! as @hwnd said `this matches Unicode newlines sequences` this must be the case. – Dima Deplov Jun 24 '14 at 16:35
1

This should work in php:

$re = '/(.+)\n\n/'; 
$str = "first string\n\nsecond string\n\nother strings bla bla bla"; 
if (preg_match($re, $str, $matches))
   echo $matches[1];
else
   echo "nope";

OUTPUT:

first string

It is important to use double quotes in input $str so that \n is interpreted as newline character.

Working Demo

anubhava
  • 664,788
  • 59
  • 469
  • 547
1

Use \R instead for this case. By default this matches Unicode newline sequences.

preg_match('/(.+)\R+/', $_POST['text'], $title);
echo $title[1];

Reference:

Community
  • 1
  • 1
hwnd
  • 65,661
  • 4
  • 77
  • 114
  • thanks for your response, Danijel was the first who offer this and this is work for me, thanks for help. – Dima Deplov Jun 24 '14 at 16:37
  • @flinth no worries, I would check out the reference answer if you ever run into this problem again, it explains `\R` – hwnd Jun 24 '14 at 16:38