Laurens Mäkel
Laurens Mäkel

Reputation: 815

PHP Remove everything except numbers from string

I am using AJAX to retrieve the ID of a certain HTML element. The HTML ID is constructed like "sqlitem_1", "sqlitem_2", "sqlitem_3" etc. and each number corresponds to a record in the database.

I tried preg_replace('/\D/', '', $item);where $item is the string I need to cut, but this didn't do the trick.

Upvotes: 2

Views: 8919

Answers (2)

Stevie G
Stevie G

Reputation: 6168

This could be done either server side (PHP) or if you wanted to preserve the variable name you could use the JavaScript Split function.

JS Split Function (Client Side)

var myVar = "sqlitem_1";
var tmp = str.split("_");

and then access each element using tmp[0] etc

https://www.w3schools.com/jsref/jsref_split.asp

OR

PHP (Server Side)

$ITEMTMP=explode("_", $item);
$itemnumber=$ITEMTMP[1];

http://php.net/manual/en/function.explode.php

Upvotes: 0

mrun
mrun

Reputation: 744

Please note that preg_replace doesn't change the argument but rather returns the new value. You might wanna check the preg_replace manual. So what you need to do is assign the returned value

$item = preg_replace('/\D/', '', $item);

instead.

Upvotes: 13

Related Questions