[英]PHP Remove everything except numbers from string
I am using AJAX to retrieve the ID of a certain HTML element. 我正在使用AJAX检索某个HTML元素的ID。 The HTML ID is constructed like "sqlitem_1", "sqlitem_2", "sqlitem_3" etc. and each number corresponds to a record in the database.
HTML ID的结构类似于“ sqlitem_1”,“ sqlitem_2”,“ sqlitem_3”等,每个数字都对应于数据库中的一条记录。
I tried preg_replace('/\\D/', '', $item);
我尝试了
preg_replace('/\\D/', '', $item);
where $item
is the string I need to cut, but this didn't do the trick. $item
是我需要剪切的字符串,但这并不能解决问题。
Please note that preg_replace
doesn't change the argument but rather returns the new value. 请注意,
preg_replace
不会更改参数,而是返回新值。 You might wanna check the preg_replace manual. 您可能想查看preg_replace手册。 So what you need to do is assign the returned value
所以您需要做的就是分配返回值
$item = preg_replace('/\D/', '', $item);
instead. 代替。
This could be done either server side (PHP) or if you wanted to preserve the variable name you could use the JavaScript Split function. 这可以在服务器端(PHP)上完成,或者如果您想保留变量名,则可以使用JavaScript Split函数。
JS Split Function (Client Side) JS拆分功能(客户端)
var myVar = "sqlitem_1";
var tmp = str.split("_");
and then access each element using tmp[0] etc 然后使用tmp [0]等访问每个元素
https://www.w3schools.com/jsref/jsref_split.asp https://www.w3schools.com/jsref/jsref_split.asp
OR 要么
PHP (Server Side) PHP(服务器端)
$ITEMTMP=explode("_", $item);
$itemnumber=$ITEMTMP[1];
http://php.net/manual/en/function.explode.php http://php.net/manual/zh/function.explode.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.