Reputation: 9
I want to extract a portion of a string between two points in a string.
My input string is {you: awesome; feeling good}
I want to get the words feeling good
between ;
and }
using PHP.
Upvotes: -1
Views: 282
Reputation: 48073
By using a regex pattern, you avoid needing to generate a temporary array or performing separate extraction and sanitization steps.
Code: (Demo)
$string = "{you: awesome; feeling good}";
echo preg_replace('/[^;]*; ([^}]*).*/', '$1', $string);
// feeling good
The pattern matches the entire string.
Start matching zero or more non-semicolon characters, then a space. Then capture zero or more non-closing-parenthesis characters. Then match the rest of the string. Replace the full string with the captured middle segment.
Upvotes: 0
Reputation: 16117
You can use explode()
in PHP for split string.
Example 1:
$string = '{you: awesome; feeling good}'; // your string
preg_match('/{(.*?)}/', $string, $match); // match inside the {}
$exploded = explode(";",$match[1]); // explode with ;
echo $exploded[1]; // feeling good
Example 2:
$string = '{you: awesome; feeling good}'; // your string
$exploded = explode(";", $string); // explode with ;
echo rtrim($exploded[1],"}"); // rtrim to remove ending }
Upvotes: 0
Reputation: 96
Other option would be....
$str = "{you: awesome; feeling good}";
$str = trim($str,"{}");
echo substr($str,strpos($str,";")+1);
Upvotes: 0
Reputation: 1554
$arr = explode(';', trim("{you: awesome; feeling good}", '{}'));
$feel_good_string = trim($arr[1]);
echo $feel_good_string;
Upvotes: 3