phpparsingphp-parse-errorphp-parser

Limit echo of variable in PHP to get the desired characters


$response var has a component called custom_test_name which looks like below:

[Test_Name]ad.no.check1.check2.check3

and here is the small PHP code:

<?php
    echo "<class="."com.tests.".$response["custom_test_name"][1]."</class>";
?>

This prints the <class=com.tests.[</class>..check first character [ of custom_test_name and similarly echoing of ["custom_test_name"][2] prints T, [3] prints e....However, how to print/echo only the specifics in this case?. For eg. echoing just this ad.no.check1.check2.check3 and eliminating out that [Test_Name]. Is there a way we can specify the range/some other approach?


Solution

  • If custom_test_name is always going to begin with [Test_Name] you can remove it with something like

    $trimmed = str_replace('[Test_Name]', '', $response->custom_test_name);
    echo "<class="."com.tests." . $trimmed . "</class>";
    

    If it's not always going to be like that but is going to start with [something], you can use something like

    $trimmed = preg_replace("/(\[.*\])/", '', $response->custom_test_name);
    echo "<class="."com.tests." . $trimmed . "</class>";