Robin Alexander
Robin Alexander

Reputation: 1004

Remove spaces in front of any first character and after any last character

I would like to trim all spaces in front in any first character (except space, could be a number or an alphabetic character) and after any last character. Using /([A-Z ])\w+/, actually did good, but my $outputdoesn't. What do I have to do to get 'Any Word' in the end? And this should work for any number of words not only two inside the spaces.

$text = '                   Any Word                ';

preg_match_all('/([A-Z ])\w+/', $text, $output);

var_dump($output);

Thanks for your help!

Upvotes: 0

Views: 2074

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

If you really want to use a regex here, you can try matching with the pattern \s+(.*)\s+:

$string = '                   Any Word                ';
preg_match('/\\s+(.*)\s+/', $string, $m);
echo $m[1];

Output:

Any Word

However, you could also use trim().

Demo

Upvotes: 0

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

You can use trim function that remove any space from start and end of string:

$text = '                   Any Word                ';

$output = trim($text);

var_dump($output);

Upvotes: 1

LF-DevJourney
LF-DevJourney

Reputation: 28564

what about trim(), it should work for you. Check the live demo.

Upvotes: 0

Related Questions