2

I need to identify a string that can contain 1- 6 # symbols inside another string and retrun the start position of the substring and the substring itself.

for example:

example ## string => [strpos=> 9, stren => 2]

so far I have this:

/["#"]{1,6}/gm

Can anyone help?

5
  • strpos will give you the position. Commented Jul 13, 2018 at 15:47
  • there is no such thing as "a string in a string" Commented Jul 13, 2018 at 15:47
  • @PhilippSander ... just out of curiosity, how would you define a substring then? Commented Jul 13, 2018 at 15:53
  • Note you should not use g modifier in PHP regex, and m is not necessary here since there is no ^ and $. Commented Jul 13, 2018 at 15:53
  • And, what do you intend to do with the offset information ? And, you won't get a length value in any php regex functions. Unless this is for educational purposes, maybe explain what you're trying to do. Commented Jul 13, 2018 at 16:00

1 Answer 1

3

You may use preg_match (or preg_match_all to get multiple matches) with the PREG_OFFSET_CAPTURE argument:

$str = "example ## string";
if (preg_match('~#{1,6}~', $str, $m, PREG_OFFSET_CAPTURE)) {
    print_r($m);
}

See PHP preg_match reference:

PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

See the PHP demo, output:

Array
(
    [0] => Array
        (
            [0] => ##
            [1] => 8
        )

)
Sign up to request clarification or add additional context in comments.

Comments

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.