Reputation: 7358
I've a question.
I have a string, like this:
hello, I am a string, -how are you?-
.
And I want to put any text in - -
sign in another variable and remove it from original string (in short: cut it!).
How can I do it? I should do it with preg_match
or preg_split
?
If you help me, I will grateful to you!
Upvotes: 0
Views: 214
Reputation: 105914
It's really two separate operations, but you can use the same pattern for both
$str = "hello, I am a string, -how are you?-";
$pattern = "/-(.*?)-/";
if ( preg_match( $pattern, $str, $matches ) )
{
$matched = $matches[1];
$str = preg_replace( $pattern, '', $str );
echo $matched, PHP_EOL, $str;
}
Note that this assumes that (and therefore only works when) only one section of text is demarcated by -
Upvotes: 1
Reputation: 32776
I believe this is what you are looking for is along the lines of:
preg_match("/\-[\d,\w,\s]+-/gi",'blah blah -hello world-',$myvar)
Now you can use $myvar
. It'll return an array of results, so in this case you could use $myvar[0]
and it'll return the first one -hello world-
Upvotes: 0
Reputation: 4688
A simple string split using explode
(no regex needed) may help:
$s = 'hello, I am a string, -how are you?-';
$parts = explode('-', $s);
print_r($parts);
// Prints:
// Array
// (
// [0] => hello, I am a string,
// [1] => how are you?
// [2] =>
// )
You can also use trim
functions to remove whitespace.
Upvotes: 0