2

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 achive 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 delet 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 atm: "/(?<=\D\s|^)[a-z]/i"

Pleas help - Thanks a lot!

1
  • 1
    does 'test1234' change to 't1234' or 'test1234'? Jan 28, 2015 at 12:41

4 Answers 4

1

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
0
0

Expanding the regexp you used to catch numbers should work.

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

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.