0

I'm trying to use the combo of $ and m modifier in preg_match_all.

preg_match_all('/.y$/m',$text,$matches);

basically I'm trying to get the last 2 letters of each line that ends with y, and this code works ok with this string.

$str2 = "helloly\nhelloby\nhelloty\n";

but when I try to use the same with data coming from a textarea element i only get the last line. same case is with heredoc and nowdoc. I want to understand how I can use regex with the m modifier on heredoc or multiline data from textarea

EDIT : this is the full code iam using for the test

the problem seems to be related to how newlines are interperted since when i changed the line seperator type in the php document heredoc/nowdocs are working fine. but post data still only matches the last line, I'll add the environment just incase Windows 10 x64 OSpanel 5.2.2 Apache 2.4-php7.0-7.1 PHP-7.1_64x

    <?php

$str2 = "helloly\nhelloby\nhelloty\n";

$str = <<<HERE
helloly
helloby
helloty
HERE;

$text = $_POST['textarea2'];
$matches=[];
$pr = 
var_dump(preg_match_all('/.y$/m',$str,$matches));
var_dump($matches);

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<form action="/" method="post">
    <textarea name="textarea2" style="resize:none"></textarea>
    <button type="submit">sub</button>
</form>

</body>
</html>
Kirill.bpp
  • 13
  • 3
  • Look, [it works](https://3v4l.org/TgVcn). Please show an example where it does not. – Wiktor Stribiżew Jan 01 '20 at 16:09
  • @WiktorStribiżew I have tested the code on this site and it does seem to work, so it got me thinking it has something to do with my local environment, and it does when i change the file newline from CRLF to LF heredoc works well, but the post data still gives same result – Kirill.bpp Jan 01 '20 at 16:38
  • Well, try `'/(*ANY).y$/m'` or `'/(*ANYCRLF).y$/m'` – Wiktor Stribiżew Jan 01 '20 at 16:52
  • @WiktorStribiżew thank you! your regex does work but seemed also as a workaround in some way without understanding where the problem is. some what more universal solution was before running preg_* doing a str_replace("\r\n","\n",$str). – Kirill.bpp Jan 01 '20 at 17:19
  • The `(*ANY)` PCRE verb is a **solution**. `str_replace("\r\n","\n",$str)` is a specific workaround that does not take into account all Unicode vertical whitespace. – Wiktor Stribiżew Jan 01 '20 at 22:09
  • @WiktorStribiżew Yes, my initial suggestion actually is wrong after reading the duplicate article(Thanks alot :)!). It seems that the windows version of PHP is always compiled this way(at least the versions that iv'e tried) – Kirill.bpp Jan 02 '20 at 06:45

0 Answers0