开发者

Get first part of string in php

开发者 https://www.devze.com 2023-04-13 04:56 出处:网络
I\'ve got a string of: test1.doc,application/msword,/tmp/phpDcvNQ5,0,23552 I want the first part before the comma. How do I get the first part \'test1.doc\' on it\'s own without the rest of the st

I've got a string of:

test1.doc,application/msword,/tmp/phpDcvNQ5,0,23552 

I want the first part before the comma. How do I get the first part 'test1.doc' on it's own without the rest of the string?

开发者_如何学Python

The string came from an array I imploded:

$uploadFlag=implode( ',', $uploadFlag );
echo $uploadFlag;

If it's easier to extract just the first value off the array on it's own that would also do the job. I don't think the array has any keys.

Thanks in advance.


echo $uploadFlag[0];

Uh, try that in place of that whole chunk of code. Since you're imploding it, you could just grab the first piece instead. That ought to echo the proper value!


$parts = explode(',', $uploadFlag);
$firstPart = $parts[0];


Use this code:

$part = substr($uploadFlag , 0, strpos($uploadFlag , ','));


To extract it from the string, you can use preg_replace() for example.

$firstPart = preg_replace('/,.*$/', '', $uploadFlag);

In the above example, the regular expression replaces everything (.*) that follows the first comma (,) until the end of the string ($) with nothing ('').

Or, if you can use the $uploadFlag array before replacing it with the imploded string, then you can use reset() to go to the first element in the array and current() to extract its value.

reset($uploadFlag);
$firstPart = current($uploadFlag);


Implode is not the right function. It takes an array and combines into one string. You are trying to do the reverse operation, which is handled by explode:

    $uploadFlag=explode( ',', $uploadFlag );
    echo $uploadFlag;


echo array_shift(array_slice($uploadFlag, 0, 1)); will output the first element of your array beit an associative or numbered array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号