Home >Backend Development >PHP Problem >How to remove underline in php

How to remove underline in php

藏色散人
藏色散人Original
2021-06-10 09:41:302792browse

php method to remove underlines: first create a PHP sample file; then remove the underlines through "preg_replace( '/_[^_]*$/', '', your_string );".

How to remove underline in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

Specific questions:

How to remove underline in php?

php - How to remove the last occurrence of underscore in a string

I have a string that contains many underscores followed by words for example: "Field_4_txtbox" I need to find the last one in the string underscore and remove everything after it (including the "_") so it returns me "Field_4" but I need it to handle different lengths of trailing strings. So I can't just trim a fixed length.

I know I can do an If statement to check for certain endings like

if(strstr($key,'chkbox')) {
    $string= rtrim($key, '_chkbox');
}

but I want to do this in one go using a regex pattern, how can I do it?

Solution:

The matching regular expression will be:

/_[^_]*$/

Just replace it with ":

preg_replace( '/_[^_]*$/', '', your_string );

[Recommended learning: PHP video tutorial]

The above is the detailed content of How to remove underline in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn