comez comez - 1 month ago 12
PHP Question

Extract character from string in "td" tag

I have a table:

<tr>
<td id="rk1">First RK</td>
<td id="rk1_1">09231</td>
</tr>
<tr>
<td id="rk2">Second RK</td>
<td id="rk2_1">60234</td>
<td id="rk2_2">69260</td>
</tr>
<tr>
<td id="rk3">Third RK</td>
<td id="rk3_1">30224</td>
<td id="rk3_2">30302</td>
<td id="rk3_3">20280</td>
<td id="rk3_4">82122</td>
</tr>


And I want to extract content like this:

result1 = 23 //("rk1 / column 1 / character 3" and "rk2 / column 1 / character 4" )
result2 = 62 //("rk2 / column 2 / character 1" and "rk3 / column 3 / character 3")
result3 = 91 //("rk2 / column 2 / character 2" and "rk3 / column 4 / character 3")
...


Use array (condition) to extract string:

("rk1/1/3 and rk2/1/4", "rk2/2/1 and rk3/3/3", "rk2/2/2 and rk3/4/3",...)


How can i do this task?

Answer

You could do it with the code below, but the way you format your parameters is kind of weird, and may produce errors if not formatted correctly.

var parameters = ["rk1/1/3 and rk2/1/4", "rk2/2/1 and rk3/3/3", "rk2/2/2 and rk3/4/3"];

// For each set of parameters, execute extract_content
for (var i = 0; i < parameters.length; i++) {
  console.log('Result for "' + parameters[i] + '":');
  console.log(extract_content(parameters[i]));
}

function extract_content(params) {
  // Split selections, to get something like ["rk1/1/3", "rk2/1/4"]
  var selections = params.split(' and '),
      res = '';
  // For each selection
  for (var i = 0; i < selections.length; i++) {
    // Split it on slashes, to get ["rk1", "1", "3"]
    var parts = selections[i].split('/'),
        // Get the element with ID "rk1_1"
        elem = document.getElementById(parts[0] + '_' + parts[1]);
    // If the element exists
    if (elem) {
      // Add the character at position X to the result
      res += elem.textContent.trim()[parts[2] - 1];
    }
  }
  // Convert result to a number and return it
  return +res;
}
<table>
  <tr>
    <td id="rk1">First RK</td>
    <td id="rk1_1">09231</td>
  </tr>
  <tr>
    <td id="rk2">Second RK</td>
    <td id="rk2_1">60234</td>
    <td id="rk2_2">69260</td>
  </tr>
  <tr>
    <td id="rk3">Third RK</td>
    <td id="rk3_1">30224</td>
    <td id="rk3_2">30302</td>
    <td id="rk3_3">20280</td>
    <td id="rk3_4">82122</td>
  </tr>
</table>