简体   繁体   English

PHP从字符串中删除除数字以外的所有内容

[英]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.

相关问题 除了PHP字符串中的字母以外的所 - Remove everything except letters from PHP string PHP字符串删除除中心数字以外的所有内容? - PHP string remove everything but center numbers? 使用正则表达式从字符串中删除除图像标签以外的所有内容 - Remove everything except image tag from string using regular expression 从字符串中删除除具有特定模式的日期以外的所有内容 - Remove everything from a string except a date with a certain pattern 如何从字符串中删除除数字之外的所有内容并将它们放入数组中? - How to remove everything from a string except for the number and put these in an array? php-如何从字符串中切出所有内容,但在php中除了其中的某些部分? - How to cut out everything from a string except certain part of it in php? PHP删除除字母和连字符( - )之外的所有内容 - PHP remove everything except letters and a hyphen (-) php-去除所有字符串,除了ASCII和表情符号 - php - strip a string of everything except ascii and emoji 在 PHP 中删除从字符第一次出现到字符串末尾的所有内容 - Remove everything from the first occurrence of a character to the end of a string in PHP PHP - 从字符串中删除除日期以外的所有内容的正则表达式 - PHP - Regular expression to remove everything else but dates from a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM