Home > Back-end >  How to get NUMBER in a string "constant-string-NUMBER-*"?
How to get NUMBER in a string "constant-string-NUMBER-*"?

Time:01-09

I've strings like constant-string-NUMBER-* where

  • constant-string- is a costant string (that I know and can use in the effort of getting the NUMBER) e.g. fix-str-
  • NUMBER is any natural number
  • -* can be any string

String-result examples:

fix-str-0
// result: 0

fix-str-0-another-str
// result: 0

fix-str-123
// result: 123

fix-str-456789
// result: 456789

fix-str-123456789-yet-another-str
// result: 1234567899

fix-str-999999-another-str-123
// result: 999999

I would like to extract the NUMBER from those strings in PHP so that I can associate this number to a variable e.g. $numberFromString = ?.

Any insight?

CodePudding user response:

Try this:

fix-str-(\d )
  • fix-str- match this string.
  • (\d ) followed by one or more digit, and save the number inside the first capturing group.

See regex demo

<?php 


$str ="fix-str-123456789-yet-another-str fix-str-234";

$pattern = "/fix-str-(\d )/";

preg_match($pattern, $str, $arr1); //Find only the first match.

echo "The first match: " . $arr1[1]; //Output: 123456789

echo "\n\n\n";

preg_match_all($pattern, $str, $arr2); //Find all the matches.

echo "All the matches: " . implode(',', $arr2[1]); //Output: 123456789,234


?>

CodePudding user response:

To extract the NUMBER from the string in PHP, you can use a regular expression to match the pattern of the string and capture the NUMBER portion.

Here's an example of how you could do this:

$string = 'fix-str-123-abc';

// Use a regular expression to match the pattern of the string
// and capture the NUMBER portion
preg_match('/^fix-str-(\d )-/', $string, $matches);

// The NUMBER will be the first element in the $matches array
$numberFromString = $matches[1];

The regular expression '/^fix-str-(\d )-/' uses the following pattern:

  • '^' matches the start of the string
  • 'fix-str-' matches the constant string
  • '(\d )' captures one or more digits (the NUMBER)
  • '-' matches the dash after the NUMBER

This regular expression will match a string that starts with 'fix-str-', followed by one or more digits, followed by a dash. The digits will be captured and can be accessed in the '$matches' array.

Note that this regular expression assumes that the NUMBER will always be a series of digits. If the NUMBER could also contain letters or other characters, you will need to adjust the regular expression accordingly. Hope this helps you! :)

CodePudding user response:

You can represent a string as an array of characters. Use the PHP substr() Function, where the second argument is the number from which your string is left.

Example. Return "world" from the string:

<?php
echo substr("Hello world",6);
?>

Info from here: https://www.w3schools.com/php/func_string_substr.asp

  • Related