views:

121

answers:

6

How to trim a part of a string, and save it in a particular string in MySQL using PHP?

Example:

If a string has the value "REGISTER 11223344 here"

How can I cut "11223344" from the string?

+1  A: 

assuming 11223344 is not constant

$string="REGISTER 11223344 here";
$s = explode(" ",$string);
unset($s[1]);
$s = implode(" ",$s);
print "$s\n";
That'll get him `11223344`, which is (I think) the inverse of what he wants.
Dominic Rodger
How so? He's unsetting the array index that *contains* "11223344".
Joel Alejandro
i made the adjustments after Dominic's comments.
+2  A: 

If you're specifically targetting "11223344", then use str_replace:

echo str_replace("11223344", "", "REGISTER 11223344 here");
Dominic Rodger
For somebody that has 14k SO score, are you really dumb enough to think he specifically wants 11223344, obviously the numbers are a placeholder and will always change.
TravisO
@TravisO - there's no need to be rude. I posted a comment asking him to clarify what output he wants, in the absence of a clarification, this is (in my view at least) the most useful answer I can give. Making the assumption that need needs to use a regex may be valid, but it is an assumption.
Dominic Rodger
A: 

Do the following

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER(.*)here/','',$string);

This would return "REGISTERhere"

or

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER (.*) here/','',$string);

This would return "REGISTER here"

Roland
A: 

substr() is a built-in php function which returns part of a string. The function substr() will take a string as input, the index form where you want the string to be trimmed. and an optional parameter is the length of the substring. You can see proper documentation and example code on http://php.net/manual/en/function.substr.php

NOTE : index for a string starts with 0.

Umair
A: 

You can use str_replace, which is defined as:

str_replace  ( $search  , $replace  , $subject )

So you can write the code as:

$subject = "REGISTER 11223344 here";
$search = "11223344"
$trimmed = str_replace($search, "", $subject);
echo $trimmed

For the full reference check: http://php.net/manual/en/function.str-replace.php

None
+1  A: 

When you need rule based matching, you need to use regex

$string = "REGISTER 11223344 here";
preg_match("/(\d+)/", $string, $match);
$number = $match[1];

That will match the first set of numbers, so if you need to be more specific try:

$string = "REGISTER 11223344 here";
preg_match("/REGISTER (\d+) here/", $string, $match);
$number = $match[1];
TravisO