0

With PHP, I am trying to select only --- select.this --- part from the below string

// String
abcd efg select.this 123 456

Goal : get the - select.this - part of the string above into a variable (everything before and after a period till the occurrence of a blank space)

Would I need a regular expression for this ?

Manu
  • 81
  • 9
  • _Would I need a regular expression for this ?_ Yes – B001ᛦ Jul 20 '20 at 21:00
  • Does this answer your question? [How to get a substring between two strings in PHP?](https://stackoverflow.com/questions/5696412/how-to-get-a-substring-between-two-strings-in-php) – A.J Jul 21 '20 at 01:09

2 Answers2

0

You can use regular expression to select such values, eg.

<?php
$text = 'abcd efg select.this 123 456';
$matches = [];
preg_match('/^abcd efg (.+) 123 456$/', $text, $matches);
print_r($matches);

The following will output:

Array
(
    [0] => abcd efg select.this 123 456
    [1] => select.this
)

You you know the exact length of strings before and after your phrase you can use substr() function – that solution will be faster than using regular expressions.

Michał Szczech
  • 466
  • 4
  • 17
0

Just write a regular expression getting everything around the "." and use preg_match to overwrite the string (or assign it to a new variable).

You could do this:

$str = "abcd efg select.this 123 456";
preg_match("/\w*?\.\w*/i", $str, $str);
echo $str[0];

//Output = select.this
MinganB
  • 18
  • 3