0

Hello I'm not good with regex and I would really appreciate if someone could help me out. I need a regex function that will find all patterns that start with : and are followed by at least 1 letter and maybe numbers until next occurrence of a symbol.

For example :hi/:Username@asdfasfasdf:asfs,asdfasfasfs:asdf424/asdfas

As you can see here there are 4 occurences. What I would like to achieve is to end up with an array containing:

['hi','Username','asfs','asdf424']

PS. Letters might be in other languages than english.

Downvoting for no reason... congrats

This is what I'm using so far but I suppose it would be easier with regex

public function decodeRequest() {

    $req_parts = $this->getRequestParams(); // <-array of strings


    $params = array();

    for ($i=0; $i < count($req_parts); $i++) {

        $starts = mb_substr($req_parts[$i], 0, 1, 'utf-8');
        $remains = mb_substr($req_parts[$i], 0, mb_strlen($req_parts[$i]), 'utf-8');

        if ($req_parts[$i] == ':') {
            array_push($params,$remains);
        }


    }

    return $params;

}
0

2 Answers 2

2

Since you want support for non-ASCII characters it is better to use \p{L} with u switch:

$s = ':hi45/:Username@asdfasfasdf:asfsŚAAÓ,asdfasfasfs:asdf424/asdfas';
if (preg_match_all('/:([\p{L}\d]+)/u', $s, $arr))
   var_dump($arr[1]);

OUTPUT:

array(4) {
  [0]=>
  string(4) "hi45"
  [1]=>
  string(8) "Username"
  [2]=>
  string(10) "asfsŚAAÓ"
  [3]=>
  string(7) "asdf424"
}
Sign up to request clarification or add additional context in comments.

7 Comments

Damn dude you have helped me in other regex question regarding htaccess clean url rewritting. :) saved my ass twice thank you again!
Thanks for remembering me and glad that it all worked out for you.
Mate may I ask something extra in case I need it. How could we modify this regexp to work untill next occurance of / or - instead of any symbol?
To match string untill next occurance of / or - you can use [^/-]+
so the complete regex would look like '/:([\p{L}\d][^/-]+)/u' ?
|
1
/:([a-zA-Z][a-zA-Z0-9]*)/
  • you need at least a letter [a-zA-Z]
  • then any sequence of valid characters (letters, numbers) [a-zA-Z0-9]*

See demo

<?php
    $string = ":hi/:Username@asdfasfasdf:asfs,asdfasfasfs:asdf424/asdfas";
    preg_match_all('/:([a-zA-Z][a-zA-Z0-9]*)/', $string, $matches);
    print_r($matches[1]);

Output:

Array
(
    [0] => hi
    [1] => Username
    [2] => asfs
    [3] => asdf424
)

1 Comment

how should I modify this in order to have at least 1 letter after the : sign ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.