简体   繁体   中英

Replace all the first character of words in a string using preg_replace()

I have a string as

This is a sample text. This text will be used as a dummy for "various" RegEx "operations" using PHP.

I want to select and replace all the first alphabet of each word (in the example : T,i,a,s,t,T,t,w,b,u,a,d,f,",R,",u,P ). How do I do it?

I tried /\\b.{1}\\w+\\b/ . I read the expression as "select any character that has length of 1 followed by word of any length" but didn't work.

You may try this regex as well:

(?<=\s|^)([a-zA-Z"])

Demo

Your regex - /\\b.{1}\\w+\\b/ - matches any string that is not enclosed in word characters, starts with any symbol that is in a position after a word boundary (thus, it can even be whitespace if there is a letter/digit/underscore in front of it), followed with 1 or more alphanumeric symbols ( \\w ) up to the word boundary.

That \\b. is the culprit here.

If you plan to match any non-whitespace preceded with a whitespace, you can just use

/(?<!\S)\S/

Or

/(?<=^|\s)\S/

See demo

Then, replace with any symbol you need.

You may try to use the following regex:

(.)[^\s]*\s?

Using the preg_match_all and implode the output result group 1

<?php
$string = 'This is a sample text. This text will be used as a dummy for'
 . '"various" RegEx "operations" using PHP.';
$pattern = '/(.)[^\s]*\s?/';
$matches;
preg_match_all($pattern, $string, $matches);

$output = implode('', $matches[1]);
echo $output; //Output is TiastTtwbuaadf"R"uP

For replace use something like preg_replace_callback like:

$pattern = '/(.)([^\s]*\s?)/';
$output2 = preg_replace_callback($pattern, 
   function($match) { return '_' . $match[2]; }, $string);

//result: _his _s _ _ample _ext. _his _ext _ill _e _sed _s _ _ummy _or _various" _egEx _operations" _sing _HP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM