Reputation: 5271
$name
are strings, contains file names are something like below,
AAA_ss_01.pdf, AAA_ss_02.pdf, AAA_sd_01.pdf, BBB_ss_02.pdf, BBB_ss_4.pdf, BBB_sd_01.pdf, cc_saa_01.pdf
I'd like to add an input name value to classify items automatically.
<input name="AAA" .../> or <input name="BBB" .../> ........
PHP
if (strpos($names, 'AAA') !== false) {
echo 'AAA';
}elseif (strpos($names, 'BBB') !== false){
echo 'BBB';
}elseif (strpos($names, 'ccc') !== false){
echo 'ccc';
}else{
echo '';
}
I make a function like this
function contains($names, $string){
if (strpos($names, $string) !== false) {
echo $string;
}
}
but I am not sure if strpos is a right method I could use or there is a better one.
Thanks
Upvotes: 0
Views: 399
Reputation: 50787
If you're just looking to make an input out of the first 3 letters, you can do it quickly using the following:
foreach($names as $name):
echo '<input name="', substr($name, 0, 3) ,'" type="text"/>';
endforeach;
Upvotes: 1
Reputation: 16656
strpos
is the correct method to check if string A contains string B. It is extremely fast. You may want to use stripos
for case insensitive matching instead.
However, if $names
is an array, you must iterate over it and check every value.
foreach ($names as $name) {
if (strpos($name, 'AAA') !== false) {
echo 'AAA';
} elseif (strpos($name, 'BBB') !== false) {
echo 'BBB';
} elseif (strpos($name, 'ccc') !== false) {
echo 'ccc';
} else{
echo '';
}
}
Upvotes: 3