skip to Main Content

I have a rawurlencoded string and want to get everything from the beginning of a string until a rawurlencoded newline (%0A) or carriage return (%0D) or the whole string if neither are in the string.

Example

From these strings:

First%20sentence.%0D%0ASecond%20Sentence.
Just%20one%20sentence.

I want to get these strings:

First%20sentence.
Just%20one%20sentence.

Basically I would like a function similar to strtok($string, "R"), but that doesn’t work because the string is rawurlencoded and the newline and carriage return characters have been turned into a sequence of three characters each.

2

Answers


  1. Here’s a nice way to do it:

    function getFirstLine ($query)
    {
        $lines = preg_split('~%0A|%0D~', $query);
    
        return $lines[0];
    }
    

    This works in all cases:

    $a = 'First%20sentence.';
    echo getFirstLine($a), "n"; // First%20sentence.
    
    $b = 'First%20sentence.%0ASecond%20Sentence.';
    echo getFirstLine($b), "n"; // First%20sentence.
    
    $c = 'First%20sentence.%0DSecond%20Sentence.';
    echo getFirstLine($c), "n"; // First%20sentence.
    
    $d = 'First%20sentence.%0D%0ASecond%20Sentence.';
    echo getFirstLine($d), "n"; // First%20sentence.
    

    If I were using this production, I would turn the function into a method on a class, and then I would turn those four $a, $b, $c, $d statements into unit tests.

    Login or Signup to reply.
  2. Use the following to only removed the markers and any trailing characters IF they exist in the string.

    There is no reason to create an array then extract the first element from that temporary array; just remove the unwanted substring if it actually exists.

    Code: (Demo)

    echo preg_replace('/(?:%0D|%0A).*/', '', $string);
    

    More concisely: (Demo)

    echo preg_replace('/%0[AD].*/', '', $string);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search