简体   繁体   中英

Regular Expression to remove underscore and string

I need to use PHP regex to remove '_normal' from the end of this url.

http://a0.twimg.com/profile_images/3707137637/8b020cf4023476238704a9fc40cdf445 _normal .jpeg

so that it becomes

http://a0.twimg.com/profile_images/3707137637/8b020cf4023476238704a9fc40cdf445.jpeg .

I tried

$prof_img = preg_replace('_normal', '', $prof_img);

but the underscore seems to be throwing things off.

As others have stated, str_replace is probably the best option for this simple example.

The problem with your specific code is that your regex string is undelimited, you need to this instead:

$prof_img = preg_replace('/_normal/', '', $prof_img);

See PCRE regex syntax for a reference.

The underscore is treated as a normal character in PCRE and isn't throwing things off.

If you require that only _normal at the end of the filename is matched, you can use:

$prof_img = preg_replace('/_normal(\.[^\.]+)$/', '$1', $prof_img);

See preg_replace for more information on how this works.

Try using str_replace; it's much more efficient than regex for something like this.

However, if you want to use regular expressions, you need a delimiter:

preg_replace('|_normal|','', $url);

str_replace应该工作。

$prof_img = str_replace('_normal', '', $prof_img);

You just forgot to add delimiters around your regex.

http://www.php.net/manual/en/regexp.reference.delimiters.php

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

$prof_img = preg_replace('/_normal/', '', $prof_img);

$prof_img = preg_replace('#_normal#', '', $prof_img);

$prof_img = preg_replace('~_normal~', '', $prof_img);

You can use decompose the URL first, perform the replacement and stick them back together, ie

$url = 'http://a0.twimg.com/profile_images/3707137637/8b020cf4023476238704a9fc40cdf445_normal.jpeg';

$parts = pathinfo($url);
// transform
$url = sprintf('%s%s.%s', 
     $parts['dirname'],
     preg_replace('/_normal$/', '', $parts['filename']),
     $parts['extension']
);

You might note two differences between your expression and mine:

  1. Yours wasn't delimited.

  2. Mine is anchored, ie it only removes _normal if it occurs at the end of the file name.

Using non-capturing groups, you can also try like this:

$prof_img = preg_replace('/(.+)(?:_normal)(.+)/', '$1$2', $prof_img);

It will keep the required part as a match.

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