-2

Here i am having a string "one two $\alpha \beta $ three".

What i need is to get the part of string until its second occurrence of a character here it is "$" or may be group of characters "$$".

ie, output should be "one two $\alpha \beta $" and "one two $$\alpha \beta $$" if the string is "one two $$\alpha \beta $$ three".

VishnuPrasad
  • 1,078
  • 5
  • 17
  • 36

2 Answers2

1

Using the regex /.*\$.*\$/ will give you what you want.

This code

$ptrn='/.*\$.*\$/';
preg_match_all($ptrn, "one two $\alpha \beta $ three", $matches);  
echo $matches[0][0] . "<br>";
preg_match_all($ptrn, "one two $$\alpha \beta $$ three", $matches);  
echo $matches[0][0] . "<br>";

will give the following output

one two $\alpha \beta $
one two $$\alpha \beta $$

So I guess that's what you want. Or...?

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
  • FYI: this regex is only good for the current string in the original question. In real life, you should avoid `.*` if you need to limit to some number of occurrences. See [this demo](https://regex101.com/r/oL1gY2/1). – Wiktor Stribiżew Mar 10 '16 at 07:53
1

Solution with preg_match function:

$str = "one two $\alpha \beta $ three one two $$\alpha \beta $$ three";

preg_match("/[^$]+?[$]{1,2}[^$]+?[$]{1,2}/i", $str, $matches);
// [^$] - matches all symbols excepting '$'
// [$]{1,2} - symbolic class - matches only '$' symbol in quantity from 1 to 2
// ? - supply "ungreedy" matching

var_dump($matches);

// the output:  "one two $\alpha \beta $"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105