2

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.

6
  • What was your exact code that you tried out? Commented Mar 6, 2017 at 8:53
  • $item = $_GET['item']; preg_replace('/\D/', '', $item); // Haal alle non-nummeristic characters uit de string $item. echo json_encode($item); Commented Mar 6, 2017 at 8:54
  • And the outcome is just the same string.. Commented Mar 6, 2017 at 8:55
  • Yeah, that won't work. preg_replace doesn't change the original value but rather returns the new one. You might wanna check preg_replace. So you should do $item = preg_replace('/\D/', '', $item); instead. Commented Mar 6, 2017 at 8:55
  • Yeah! Great, it worked, thank you very much! Commented Mar 6, 2017 at 8:56

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.