String Manipulation in PHP
I've got a string in php it can be in one of two formats - either:
"example1" AND somethingelse = "exa开发者_开发问答mple2"
or just
"example1"
All I need is to get the data in the speechmarks, whether both or just the one.
Cheers!
preg_match( '/"([^"]*)"/' , $string, $matches )
# $matches is an array with the results
# ignore $matches[0]
# $matches[1] will contain the first string inside double-quotes
# $matches[2] will contain the second string inside double-quotes (if any)
more info here: http://www.php.net/manual/en/function.preg-match.php
If you are looking to replace text, following a certain regex would help:
http://php.net/manual/en/function.preg-replace.php
OR, if you're not wanting to replace text, you can match it using:
http://www.php.net/manual/en/function.preg-match.php
Thanks for the help, I managed it in a slightly backwards way, using the basis of bowsersenior's answer and some simple counting!
//Find amount of Speech marks
$stringCount = substr_count($newstring, '"');
if ($stringCount == 2){
preg_match( '/".*?"/' , $newstring, $matches);
foreach ($matches as $data)
{
print_r($data);
}
}else{
//Get first speech marks
preg_match( '/".*?"/' , $newstring, $matches);
foreach ($matches as $data)
{
print_r($data);
}
//Get second speech marks
$endString = substr($newstring,-4);
echo $endString;
}
精彩评论