开发者

Replace symbol if it is preceded and followed by a word character

开发者 https://www.devze.com 2023-02-02 10:43 出处:网络
I want to change a specific character, only if it\'s previous and following character is 开发者_如何转开发of English characters. In other words, the target character is part of the word and not a star

I want to change a specific character, only if it's previous and following character is 开发者_如何转开发of English characters. In other words, the target character is part of the word and not a start or end character.

For Example...

$string = "I am learn*ing *PHP today*";

I want this string to be converted as following.

$newString = "I am learn'ing *PHP today*";


$string = "I am learn*ing *PHP today*";
$newString = preg_replace('/(\w)\*(\w)/', '$1\'$2', $string);

// $newString = "I am learn'ing *PHP today* "

This will match an asterisk surrounded by word characters (letters, digits, underscores). If you only want to do alphabet characters you can do:

preg_replace('/([a-zA-Z])\*([a-zA-Z])/', '$1\'$2', 'I am learn*ing *PHP today*');


The most concise way would be to use "word boundary" characters in your pattern -- they represent a zero-width position between a "word" character and a "non-word" characters. Since * is a non-word character, the word boundaries require the both neighboring characters to be word characters.

No capture groups, no references.

Code: (Demo)

$string = "I am learn*ing *PHP today*";
echo preg_replace('~\b\*\b~', "'", $string);

Output:

I am learn'ing *PHP today*


To replace only alphabetical characters, you need to use a [a-z] as a character range, and use the i flag to make the regex case-insensitive. Since the character you want to replace is an asterisk, you also need to escape it with a backslash, because an asterisk means "match zero or more times" in a regular expression.

$newstring = preg_replace('/([a-z])\*([a-z])/i', "$1'$2", $string);


To replace all occurances of asteric surrounded by letter....

$string = preg_replace('/(\w)*(\w)/', '$1\'$2', $string);

AND

To replace all occurances of asteric where asteric is start and end character of the word....

$string = preg_replace('/*(\w+)*/','\'$1\'', $string);

0

精彩评论

暂无评论...
验证码 换一张
取 消