Search code examples
phpsubstring

PHP - How to splice a string at a certain character?


I want to make a function that grabs each line from a file after the colon. I'm having trouble slicing the string at said character.

So I want to slice this:

"date: march 27, 2017" to "march 27, 2017" "start: 12:30pm" to "12:30pm" ...etc.

Note: I don't need help writing the actual function, I just want to know how to splice the line at the first colon


Solution

  • For your case, using: $string = "date: march 27, 2017"; or $string = "start: 12:30pm";

    You can select any one of these techniques:

    *note: If there are concerns about the existence of the needle (colon or colon space) then you should employ one of the options that is false-proof, otherwise additional considerations will be necessary to catch strings without the needle.

    Use strpos() & substr() *false-proof:

    $string = ($pos = strpos($string, ": ")) ? substr($string, $pos + 2) : $string;
    

    Use strstr() & substr() *false-proof:

    $string = ($sub = strstr($string, ": ")) ? substr($sub, 2) : $string;
    

    Use explode() *requires colon space to exist:

    $string = explode(': ', $string, 2)[1];
    

    Use explode() & end() *no longer a one-liner, but false-proof:

    $array = explode(': ', $string, 2);
    $string = end($array);
    // nesting explode() inside end() will yield the following notice:
    // NOTICE Only variables should be passed by reference
    

    Use preg_replace() with a regex pattern *false-proof:

    $string = preg_replace("/^.*?:\s/", "", $string);
    

    Use preg_match() with a regex pattern not a one-liner, but false-proof:

    $string = preg_match("/^.*?:\s\K.*/", $string, $m) ? $m[0]: $string;
    

    Here is a Demo for anyone who might want to run some tests on their own snowflake case.