简体   繁体   中英

How can I take off a letter from a string in PHP?

I would like to know how can I take a character out of a string?

I have a date:

$date = "04.08.2013";

I would like to take just the first 2 zeros off. Like that:

$date = "4.8.2013"

How can I do it?

一个简洁的(读取:hacky)解决方案将是:

$date = implode('.', array_map(function($x) { return (int)$x; }, explode('.', $date)));

You can may also get it done quickly using a regex:

$new_date = preg_replace('/(?<=^|\.)0/', '', $date);

Or more simply without the lookbehind (thanks @IlmariKaronen):

$new_date = preg_replace('/\b0/', '', $date);

Demo

use explode() to separate the string into an array then use ltrim to delete "0"

ie

$date = explode(".", "04.08.2013");
$new_date = implode(".", array(ltrim($date[0],"0"), ltrim($date[1],"0"), $date[2]));

or something like that

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