Viewed   91 times

I have the following string in a variable.

 is as frictionless and painless to use as we could make it.

I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me is as frictio this output but I want output as:

 is as...

Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?

Edited:

I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.

 Answers

2

You can use the wordwrap() function, then explode on newline and take the first part:

$str = wordwrap($str, 28);
$str = explode("n", $str);
$str = $str[0] . '...';
Tuesday, December 13, 2022
1

You are close, need indexing with str which is apply for each value of Series:

data['Order_Date'] = data['Shipment ID'].str[:8]

For better performance if no NaNs values:

data['Order_Date'] = [x[:8] for x in data['Shipment ID']]

print (data)
        Shipment ID Order_Date
0  20180504-S-20000   20180504
1  20180514-S-20537   20180514
2  20180514-S-20541   20180514
3  20180514-S-20644   20180514
4  20180514-S-20644   20180514
5  20180516-S-20009   20180516
6  20180516-S-20009   20180516
7  20180516-S-20009   20180516
8  20180516-S-20009   20180516

If omit str code filter column by position, first N values like:

print (data['Shipment ID'][:2])
0    20180504-S-20000
1    20180514-S-20537
Name: Shipment ID, dtype: object
Saturday, November 5, 2022
 
2

Use the rtrim function:

rtrim($my_string, ',');

The Second parameter indicates the character to be deleted.

Sunday, December 18, 2022
 
pask23
 
3

substr() is NOT substr($string, $start, $last) it's substr($string, $start, $length). So substr('abcdef', 0, 4) returns abcd because it starts at 0 (a) and it goes for 4 letters.

Also random note: echo substr('abcdef', -1, 1); is inherently redundant since -1 only has a length of 1 so the string might as well be: echo substr('abcdef', -1);

Wednesday, September 28, 2022
 
phaker
 
1

var str = '012123';
var strFirstThree = str.substring(0,3);

console.log(str); //shows '012123'
console.log(strFirstThree); // shows '012'

Now you have access to both.

Monday, December 12, 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 :