Nigo
Nigo

Reputation: 23

Remove all spaces and non-first letters from words in a string

I'm stuck at a PHP/RegEx line.

What I am trying to achieve is the following:

I've got a String

"My new project 2015"

What I'd like to achieve is that after RegEx'ing it to look like this:

"Mnp2015"

So it should extract the first letter from each word of the string, but not the first digit or delete the digit completely.

I've got as far that I get "Mnp2", but cant seem to figure out how to "ignore" the digits.

Using following RegEx at the moment: "/(?<=\D\s|^)[a-z]/i"

Upvotes: 2

Views: 3585

Answers (5)

mickmackusa
mickmackusa

Reputation: 47894

This question only provides one sample input string so we have no way of knowing how the project strings might vary.

You don't need to use preg_match() or create any temporary arrays of matches; just use preg_replace() to remove the characters that you don't want.

\K "forgets" the previously matched letter.

Code: (Demo)

$text = 'My new project 2015';
echo preg_replace('/[a-z]\K[a-z]* /i', '', $text);
// Mnp2015

Upvotes: 0

Bart Haalstra
Bart Haalstra

Reputation: 1062

$title = 'My new project 2015 test1234';
$result = preg_replace('/(?:([a-z])[^ ]*(?: |$)| )/i', '$1', $title);
echo $result;

Upvotes: 0

David Faber
David Faber

Reputation: 12485

The regex you use above /(?<=\D\s|^)[a-z]/i won't work with PCRE regular expressions since the look-behind is not fixed width. At least, that is the error I get when I try it. It is easier in this case simply to assert a word boundary:

/\b([a-zA-Z]|\d+)/g

This matches the first character of each word starting with a letter while matching any number of digits. See Regex 101 demo here.

If you need to match Unicode letters and numbers, then you can do the following:

/\b(\p{L}|\p{N}+)/g

Upvotes: 1

vks
vks

Reputation: 67968

(?:^|(?<=\s))([a-zA-Z])[a-zA-Z]+\s*

Try this.Replace by $1 or \1.See demo

https://regex101.com/r/pM9yO9/4

Upvotes: 0

Taemyr
Taemyr

Reputation: 3437

Expanding the regexp you used to catch numbers should work.

(?<=\D\s|^)([a-z]|\d*)

Upvotes: 0

Related Questions