PHP String stripped and stored - php

I have a long string that I want everything from the first "-" on to be removed and the remaining saved.
I have tried rtrim and this does not work. can figure explode so that will not work

Use substr() with strpos().
$str = "3568206020-1201103628-13107292-0001";
//extract the substring from start to the first occurrence of the character `-`.
$str = substr($str, 0, strpos($str, "-"));
Output - 3568206020

Related

PHP wrapping last two letters of string with HTML

I am running into a problem trying to do a replacement on a few strings. Essentially what I have is a bunch of prices on my page that look like
RMB148.00
What i am trying to do is run a replace on only the last 2 numbers so i can do something like
RMB14800
Preg replace works fine for the RMB part because it is always there.
My problem is the last two numbers can be anything it all depends on the price so I cant just remove and replace, I need to just wrap HTML <sup> tags around them.
$string = $product['price'];
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
echo preg_replace('/RMB/', '<sup class="currency-sym">RMB</sup>', $string, 1);
Assuming the last two characters are digits, you could just
$string=preg_replace('/(\d\d)$/', '<sup class="currency-sym">\1</sup>', $string);
If not,
$string=preg_replace('/(..)$/', '<sup class="currency-sym">\1</sup>', $string);
should do the trick.
Alternativly use
$string=substr($string,0,-2).'<sup class="currency-sym">'.substr($string,-2).'</sup>';
Here is a regex solution that looks for the final digit notation at the end of your string.
$string = 'RMB148.00';
$string = preg_replace('/(\d+)\.(\d{2})\z/','$1<sup>$2</sup>',$string);
echo $string;
You could use the following with the explode () function
$string = explode ('.', $product['price']);
$new_string = $string[0].'<sup>'. $string [1]. '</sup>';
And do the regex for the RMB the same way.
Code.
<?php
$string = '14842.00';
$string = substr($string, 0, strlen($string) - 2) . '<sup>' . substr($string, strlen($string) - 2, 2) . '</sup>';
echo $string;
Try online sandbox.
Explanation.
substr($s, $i, $l) gets $l symbols of $s, started from $i index (indexes starts from zero).
So first substr($string, 0, strlen($string) - 2) gets all string except last two symbols.
Second substr($string, strlen($string) - 2, 2) gets only last two symbols.
More about substr.
You should use a pattern matching regex. Note the $1 in the replacement argument matches (\d{2}) in the pattern argument. preg_replace() only replaces the matched pattern. This pattern matches . followed by any two digits. Since . is not included in the replacement argument it does not show up in your $string.
$string = preg_replace('/\.(\d{2})$/', '<sup>$1</sup>', $string);
Of course, you could use one preg_replace to do what you want:
$string = preg_replace('/^(RMB)(\d+)(\.(\d{2}))?$/', "<sup class='currency-sym'>$1</sup>$2<sup>$4</sup>", $string);
The second example may be a good idea if you want DOM integrity, otherwise it creates an empty <sup></sup> when there is no decimal.

How do I remove texts after the second comma in php

How can I remove the texts in a sentence after the second comma but do nothing if it has no two commas in a sentence?
I tried the following:
substr($str, 0, strpos($str, ',', strpos($str, ',')+1))
But the problem here is if I don't have two commas in this $str, the funtion outputs nothing, I'm getting a blank area.
Is there anyway to check the existence of two commas and remove text after the second comma or do nothing otherwise.
Try this:
$commasCount = count(explode(',', $str));
if ($commasCount > 2) {
$str = substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
}
A more elegant approach, without using string functions and reusing the array as we need it to count the number of commas anyway (and avoiding regex madness for readability):
$text_segments = explode(',', $str);
if( count($text_segments) > 2 ) {
$str = $text_segments[0] . ',' . $text_segments[1];
}
Just check the # of occurrences first:
if (substr_count($str, ',') >= 2)
substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
Or you could do it with preg_match() but it would be slower:
if (preg_match('/([^,]*,){2}/', $str, $match))
$str = $match[1];
Or in a single step (ala adeneo above, but altered to fit the instructions)
$str = preg_replace('/((?:[^,]*,){2})?(?:.*)$/', '$1', $str);
You'll notice the initial characters with comma at the end are made optional by the question-mark at the end of (...)? so it will get the correct value regardless.
Assuming that you want to remove the second comma and all subsequent characters (because of your selected answer), using regex is very concise and direct and can be written without any pre-checking and conditions.
Match the first the first occurring comma, match one or more non-comma characters, then forget those characters with \K, then explicitly match the second comma and all remaining characters -- to be replaced with an empty string.
Code: (Demo)
$str = "a,b,c,d";
var_export(
preg_replace("/,[^,]+\K,.*/", '', $str)
);

PHP remove and delete something after one special character

I have a very simple PHP question about replacing in string.
For example, our string is this :
This is a test - spam text
and i need to convert this string to this :
This is a test
I mean i want to detect the place of - charachter and delete everything after that.
How to do it ?
One of the possible solutions:
$result = substr($str, 0, strpos($str, '-'));
use substr to return part of a string and strpos to find the position of the first occurrence of a substring in a string
$str = 'This is a test - spam text';
$newStr = substr($str, 0, strpos($str, '-'));
// start ^ end ^
Try
$str = "This is a test - spam text";
$str = substr($str, 0, strpos( $str, '-'));
strpos() detects where - is.
You can use Regular expressions to match anything after the - character.
This should work
/-.*/
When you match the string then you can replace the content using simple string functions.

Get first string before separator?

I have strings with folowing structure:
7_string_12
7_string2_122
7_string3_1223
How I can get string before second "_" ?
I want my final result to be :
7_string
7_string2
7_string3
I am using explode('_', $string) and combine first two values, but my script was very slow!
$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));
echoes
7_string
no matter what's at the begining of the string
If it always starts with 7_ you can try this:
$string = substr($text, 0, strpos($text, '_', 2));
The strpos() searches for the first _ starting from character 3 (= s from string). Then you use substr() to select the whole string starting from the first character to the character returned by strpos().
$s1 = '7_string_12';
echo substr($s1, 0, strpos($s1, '_', 2));

How to extract a substring from a string in PHP until it reaches a certain character?

I have part of a PHP application which assess a long string input by the user, and extracts a number which always begins 20 characters into the string the user supplies.
The only problem is that I don't know how long the number for each user will be, all I do know is the end of the number is always followed by a double quote (").
How can I use the PHP substring function to extract a substring starting form a specific point, and ending when it hits a double quote?
Thanks in advance.
You can use strpos to get the first position of " from the position 20 on:
$pos = strpos($str, '"', 20);
That position can then be used to get the substring:
if ($pos !== false) {
// " found after position 20
$substr = substr($str, 20, $pos-20-1);
}
The calculation for the third parameter is necessary as substr expects the length of the substring and not the end position. Also note that substr returns false if needle cannot be found in haystack.
$nLast = strpos($userString , '"');
substr($userString, 0, $nLast);
<?
$str = substring($input, 20, strpos($input, '"') - 20);
echo $str;
?>
Or something like that etc.
find first occurrence of double quote after 20 chars, substract 19 - that gives you length of desired substring:
$dq = strpos($string,'"',19); //19 is index of 20th char
$desired_string = substr($string,19,$dq-19);
Going to just add on to Gumbo's answer in case you need help with the substring function:
$pos = strpos($str, '"', 20);
$substring = substr($str, 20, $pos);

Categories