Question:

What is the php regular expression to get everything before a certain character?

by  |  earlier

0 LIKES UnLike

For instance, I have the following string:

table:column

I need to get "table" as the result of the php regular expression.

So, I need everything before the ":" symbol

After that regular expression is performed, I would also like to get everything after the ":" symbol, or "column" as well.

 Tags:

   Report

4 ANSWERS


  1. Regular expressions are not used for this. Use tokenizing - function strtok, I believe.


  2. I agree with Dware.  Don't do more work than you need to.  It really depends on how sure you are of what can be in the original string.  You can also add an optional parm to explode(), if for instance, in your example you had table:column:1 and you still wanted to keep the column:1 together (i.e. NOT explode them) - you could say explode(':', $myString, 2); - which will explode into a maximum of 2 parts.  So your [0] entry would have "table" and your [1] would have "column:1".

  3. If you only have one ":" symbol in the string, you can use this:

    $string = explode(":", $string);

    This puts the two halves into an array. So:

    $table = $string[0];

    $column = $string[1];

  4. My regular expressions are rusty and my experience is from Perl, but in principle PHP borrows much things from Perl.

    In Perl You would write $scannedtext=~/(.*)\:(.*)/

    And then You have variables $1 and $2 that correspond to the values in the brackets.

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.