0

Lets say we have these 4 strings:

  1. string1 = "Hello my name is 'George' and im fine";
  2. string2 = "Hello my name is 'Mary' and im fine";
  3. string3 = "Hello my name is 'Peter' and im fime";
  4. string4 = "Hello my name is 'Kate' and im fine";

How can we extract only the parts of the strings that contains a name in '' ?

Thanks in advance!

4 Answers 4

2

you should probably use regular expressions:

preg_match("/'(.+?)'/", $string, $matches);
print_r($matches);

See more on http://php.net/preg_match and http://lt.php.net/preg_match_all

Sign up to request clarification or add additional context in comments.

1 Comment

I believe you need to escape the single quotes.
1
$pieces = explode("'", $string);
echo $pieces[1];

Comments

0

You can use the explode function to split the string into an array based on a delimiter in you particular case, the apostrophe would work to delimit the string so that the following code would yield your answer:

$tokens= explode("'", "Hello my name is 'Kate' and im fine");
//The value you require is now found in $tokens[1];
echo $tockens[1];

Alternatively you could use the preg_match to store regular expression matches against particular groups in the regular expresion:

$pattern = "Hello my name is '(.*)' and im fine";
preg_match ($pattern ,  "Hello my name is 'Kate' and im fine", $matches)
//The value you require is now found in $matches[1];
echo $matches[1];

1 Comment

I have this : $string1 = "My name is 'Kate' and im fine"; $pattern = "My name is '(.*)' and im fine"; preg_match($pattern , $string1, $matches); //The value you require is now found in $matches[1]; but it returns me this error : Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash echo $matches[1];
0
$string1 = "Hello my name is 'George' and im fine";
preg_match_all("/\'(.*)\'/",$string1,$matches,PREG_SET_ORDER);
echo $matches[0][1];

Above will match the string of any length between the single quotes. If you wish to match a single word with single quotes '\w+' in place of '.*' will also do.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.