Reputation: 588
I need to get two strings from one.
$string = "Service rating : good<br/>Product : good";
should return:
$service = 'good';
$product = 'good';
and
$string = "Service rating : Excellent service!<br/>Product : Outstanding product - this is the second scarf I've ordered.";
should return:
$service = 'Excellent service!';
$product = 'Outstanding product - this is the second scarf I've ordered.';
How can I best achieve this?
Upvotes: 0
Views: 48
Reputation: 3695
Just an alternative using preg_match_all():
Basically:
([a-zA-Z\s]+) : ([a-zA-Z\s-\']+)
Search for a group of words with the allowed chars inside the square brackets, with a semicolon between them.You can then apply your logic to handle the resulting array.
$string1 = "Service rating : good<br/>Product : good";
$string2 = "Service rating : Excellent service!<br/>Product : Outstanding product - this is the second scarf I've ordered.";
function getRate($string) {
preg_match_all('#([a-zA-Z\s]+?) : ([a-zA-Z\s-\']+)#', $string, $matches, PREG_SET_ORDER);
return $matches ?: false;
}
var_dump(getRate($string1));
var_dump(getRate($string2));
Upvotes: 0
Reputation: 433
You can separate the string using the explode
function 2 times. First - to separate the service from product using the tag <br/>
in the middle.
The second use will get the corresponding status - using explode with the string " : "
Here is the code
<?php
$input = "Service rating : good<br/>Product : good";
list($service, $product) = explode('<br/>', $input);
$service = explode(' : ', $service);
$product = explode(' : ', $product);
echo $service[1];
echo "<br>";
echo $product[1];
?>
Upvotes: 1
Reputation: 2702
You could use regular expressions for your solution. I give an example:
$string = "Service rating : good<br/>Product : good";
$re = '/^.*\:\s*(?:(?<service>[\w\s]+)\<br\/>).*\:\s*(?<product>[\w\s]+)$/';
if (preg_match($re, $string, $matches))
{
$service = $matches['service'];
$product = $matches['product'];
}
var_dump($service, $product);
Explanation of the used expression:
:
service
match delimited by <br/>
:
product
match (until end of string)You can play around with it here: https://regex101.com/r/vH4aZ9/2
Upvotes: 0
Reputation: 3549
$a = explode("<br/>", $string);
will provide you with an array with two values: the strings you ask for.
Then:
echo $a[0];
echo $a[1];
will print the two strings.
Or use list
to assign those values to your requested variables:
list($service, $product) = explode("<br/>", $string);
Then, as bladerz suggests, repeat the explode with ' : '
for getting the ratings for service and product.
Upvotes: 0