Viewed   59 times

I'm looking for a non-regex solution (if possible) to the following problem:

I'd like to remove everything up to and including a particular string within a string.

So, for example, £10.00 - £20.00 becomes just £20.00, maybe by providing the function with - as a parameter.

I've tried strstr and ltrim, but neither were quite what I was after.

 Answers

4

This can be achieved using string manipulation functions in PHP. First we find the position of the - character in the string using strpos(). Use substr() to get everything until that character (including that one). Then use trim() to remove whitespace from the beginning and/or end of the string:

echo trim(substr($str, strpos($str, '-') + 1)); // => £20.00

Alternatively, you could split the string into two pieces, with - as the delimiter, and take the second part:

echo trim(explode('-', $str)[1]);

This could be done in many different ways. In the end, it all boils down to your preferences and requirements.

Monday, October 3, 2022
 
3

I wouldn't recommend using explode, as it causes more issues if there is more than one comma.

// removes everything before the first ,
$new_str = substr($str, ($pos = strpos($str, ',')) !== false ? $pos + 1 : 0);

Edit:

if(($pos = strpos($str, ',')) !== false)
{
   $new_str = substr($str, $pos + 1);
}
else
{
   $new_str = get_last_word($str);
}
Wednesday, August 24, 2022
 
4

You need a Ajax call to pass the JS value into php variable

JS Code will be (your js file)

var jsString="hello";
$.ajax({
    url: "ajax.php",
    type: "post",
    data: jsString
});

And in ajax.php (your php file) code will be

$phpString = $_POST['data'];     // assign hello to phpString 
Thursday, November 10, 2022
 
2

alert('my name is: <?php echo $man; ?>' );

Friday, August 19, 2022
 
5

Is it possible? No.

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

It's the first note for the curly syntax on http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex.

Monday, October 3, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :