user3272483
user3272483

Reputation: 408

Get the string between two other strings

I have this total USD100.75 from string.I am getting the next word like this

$s = 'total USD100.75 from';
$r = preg_match_all('/(?<=(total))(\s\w*)/',$s,$matches);
print_r($matches[0]);

However i would like to get the string between two specific strings i.e total and from. How may i get the middle string?.

Upvotes: 0

Views: 92

Answers (6)

Joseph Nields
Joseph Nields

Reputation: 5661

I'm not sure of the specifics of your language, but in Java:

(?USD[0-9]+\.[0-9]{2})

would work.

  1. "USD", followed by
  2. One or more numerals, followed by
  3. Literal ".",
  4. followed by two numerals.

If you have commas, you could try:

(?USD[0-9]{1,3}(,?[0-9]{3})*\.[0-9]{2})
  1. "USD" followed by 1-3 numerals, followed by,
  2. any number of groups of: an optional comma followed by 3 numerals, followed by
  3. a decimal, followed by
  4. two digits

Upvotes: 1

user4094161
user4094161

Reputation:

@user3272483, Please check below answer for your solution.

$matches = array();
preg_match("/total (.*?) from/", 'total USD100.75 from', $matches);
print_r($matches);

Upvotes: 0

Adil Aliyev
Adil Aliyev

Reputation: 1169

The regular expressions are easy way to do it. You just need to understand the basics. You will achieve what you want with the following pattern:

total\s(.*)\sfrom

Upvotes: 0

msfoster
msfoster

Reputation: 2572

Using substr and strlen:

echo substr($string, strlen("total "), -strlen(" from"));

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

You can explode your string by space.

$s = 'total USD100.75 from';    
$s1 = explode(" ", $s);
echo $s1[1];

Output

USD100.75

Demo

Upvotes: 0

Elon Than
Elon Than

Reputation: 9765

You can also use regexp for that, eg.

'/total (.*?) from/'

Upvotes: 1

Related Questions