2

I have a string like "some words 12345cm some more words"

and I want to extract the 12345cm bit from that string. So I get the position of the first number:

$position_of_first_number = strcspn( "some words 12345cm some more words" , '0123456789' );

Then the position of the first space after $position_of_first_number

$position_of_space_after_numbers = strpos("some words 12345cm some more words", " ", $position_of_first_number); 

Then I want to have a function which return the portion of the string between $position_of_first_number and $position_of_space_after_numbers.

How do I do it?

ascripter
  • 5,665
  • 12
  • 45
  • 68
crazy sarah
  • 611
  • 4
  • 13
  • 29

2 Answers2

1

You can use the substr function. Note that it takes a starting position and a length, which you can calculate as the difference between the start and end positions.

kaya3
  • 47,440
  • 4
  • 68
  • 97
1

Since you are looking for a pattern like blank-digits-letters-blank, I would recommend a regular expression using preg_match:

$s = "some words 12345cm some more words";
preg_match("/\s(?P<result>\d+[^\W\d_]+)\s/", $s, $matches);
echo $matches["result"];

12345cm

Explaining the pattern:

  • "/.../" limits the pattern in PHP

  • \s matches any whitespace character

  • (?P<name>...) names the following pattern

  • \d+ matches 1 or more digits

  • [^\W\d_]+ matches 1 or more Unicode-letters (i.e. any character that is not a non-alphanumeric character; see this answer)

ascripter
  • 5,665
  • 12
  • 45
  • 68