テキストエリア内の改行をmysqlに格納する

echo nl2br("これ\r\nは\r\nどう表示される");

<?php

$content = $_POST&#91;'content'&#93;;
if(!empty($content)){
		echo nl2br($content);
} else {
}
?>

<form method="post" action="/">
	<textarea name="content" rows="4" cols="40"></textarea>
	<input type="submit" value="送信">
</form>

なるほどー

あれ、まてよ。pdoでmysqlに入れてみます。

$content = $_POST['content'];
if(!empty($content)){
		$value = nl2br($content);
} else {
}

try {
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8','root','',
array(PDO::ATTR_EMULATE_PREPARES => false));
} catch (PDOException $e) {
 exit('データベース接続失敗。'.$e->getMessage());
}
$stmt = $pdo -> prepare("INSERT INTO news (content) VALUES (:content)");
$stmt->bindParam(':content', $value, PDO::PARAM_STR);
$stmt->execute();
echo "成功";


?>

<form method="post" action="/">
	<textarea name="content" rows="4" cols="40"></textarea>
	<input type="submit" value="送信">
</form>
mysql> alter table news change content content varchar(100);
Query OK, 4 rows affected (0.24 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> describe news;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| content | varchar(100) | YES  |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
2 rows in set (0.03 sec)

mysql> select * from news;
+----+----------------------------------+
| id | content                          |
+----+----------------------------------+
|  1 | テスト                           |
|  2 | 10byte以上を入                   |
                    |
                    |
|  5 | ほげほげ
ふぉおお | +----+----------------------------------+ 5 rows in set (0.00 sec)

なんだ、行けるじゃん。
textareaで改行した値をmysqlに格納することは可能。

php.ini path

just write php.ini

phpinfo();

which says “/etc/php.ini”

php command: php -i

[vagrant@localhost ~]$ php -i | grep php.ini
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

php –ini

[vagrant@localhost ~]$ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/20-bz2.ini,
/etc/php.d/20-calendar.ini,
/etc/php.d/20-ctype.ini,
/etc/php.d/20-curl.ini,
/etc/php.d/20-dom.ini,
/etc/php.d/20-exif.ini,
/etc/php.d/20-fileinfo.ini,
/etc/php.d/20-ftp.ini,
/etc/php.d/20-gd.ini,
/etc/php.d/20-gettext.ini,
/etc/php.d/20-iconv.ini,
/etc/php.d/20-intl.ini,
/etc/php.d/20-json.ini,
/etc/php.d/20-mbstring.ini,
/etc/php.d/20-mysqlnd.ini,
/etc/php.d/20-pdo.ini,
/etc/php.d/20-phar.ini,
/etc/php.d/20-simplexml.ini,
/etc/php.d/20-sockets.ini,
/etc/php.d/20-sqlite3.ini,
/etc/php.d/20-tokenizer.ini,
/etc/php.d/20-xml.ini,
/etc/php.d/20-xmlwriter.ini,
/etc/php.d/20-xsl.ini,
/etc/php.d/30-mysqli.ini,
/etc/php.d/30-pdo_mysql.ini,
/etc/php.d/30-pdo_sqlite.ini,
/etc/php.d/30-wddx.ini,
/etc/php.d/30-xmlreader.ini,
/etc/php.d/40-zip.ini

locate php.ini

[vagrant@localhost ~]$ locate php.ini
-bash: locate: コマンドが見つかりません

find

[vagrant@localhost ~]$ sudo find / -name php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php55/wordpress/files/p     hp.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php55/http/php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php55/phpmyadmin/php.in     i
/home/vagrant/app/translation/php-docs-samples/appengine/php55/grpc/php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php72/wordpress/files/p     hp.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php72/trace/php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php72/errorreporting/ph     p.ini
/home/vagrant/app/translation/php-docs-samples/appengine/php72/grpc/php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/flexible/wordpress/file     s/php.ini
/home/vagrant/app/translation/php-docs-samples/appengine/flexible/memcache/php.i     ni
/etc/php.ini

すげーーーーーーー

PHP/Laravel Coding guideline

If you do not have a framework convention, there is no doubt to follow PSR-2? Really?

PSR-2: Coding Style Guide

1. Overview
– code must follow a coding style guide psr-1!??
– code must use 4 spaces for indenting, not tabs
– there must not be a hard limit on line lenght
– there must be one blank line after the namespace declation
– opening braces for classes must go on the next line, and closing braces must go on the next line
– opening braces for methods must go on the next line
– visibility must be declared on the all properties and methods
– control structure keywords must have one space after them
– opening braces for control structures must go on the same line
– opening parentheses for control structers must not have a space after them

2. General
2.1 basic coding stand
– code must follow all rules outlined in PSR-1
2.2 files
– all php files must use the unix lf line ending
– all php files must end with a single blank line
– the closing ?> tag must be ommitted from files containing only php
2.3 lines
– there must not be a hard limit on line length
– the soft limit on line length must be 120 characters
– lines should not be longer than 80 characters;
– there must not be trailing whitespace at the end of non-blank lines
– blank lines may be added to improve readability and to indicate related blocks of code
– there must not be more than one statement per line
2.4 indenting
– code must use an indent of 4 spaces, must not use tabs for indenting
– using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations.
2.5 keywords and true/false/null
php keywords must be in lower case
php constants true, false, and null must be in lower case

3. Namespace and Use Declarations
– when present there must be one blank line after the namespace declaration
– when present, all use declarations must go after the namespace declaration
– there must be one use keyword per declaration
– there must be one blank line after the use block

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;
&#91;/php&#93;

<b>4. Classes, Properties, and Methods</b>
4.1 extends and implements
- the extends and implements keywords must be declared on the same line as the class name.
- the opening brace for the class must go on its own line;

class ClassName extends ParentClass implement \ArrayAccess, \Countable
{
}

– list of implements may be split across multiple lines, where each subsequent line is indented once.

4.2 properties
– visibility must be declared on all properties
– the var keyword must not be used to declare a property
– there must not be more than one property declared per statement
– property names should not be prefixed with a single underscore to indicate protected or private visibility
– a property declaration looks like the following

class ClassName
{
    public $foo = null;
}

うおおおおおおお、 量多いな。。。
4.3 method
– visibility must be declared on all methods
– method names should not be prefixed with a single underscore to indicate protected or private visibility
– method names must not be declared with a space after the method name

public function fooBarBaz($arg1, &$arg2, $arg3 = [])
{
}

4.4 method arguments
– in all argument list, there must not be a space before each comma, and there must be one space after each comma.
– method arguments with default values must go at the end of the argument list

4.5 abstract, final and static
when present, the abstract and final declarations must precede the visibility declaration
when present, the static declaration must come after the visibility declaration

4.6 method and function call

5. control structures
– there must be one space after the control structure keyword
– there must not be a space after the opening parenthesis
– there must not be a space before the closing parenthesis
– there must be one space between the closing parenthesis and the opening brace
– the structure body must be indented once
– the closing brace must be on the next line after the body
5.1 if, elseif, else

if ($expr1){
}

5.2 switch, case
5.3 while, do while
5.4 for
5.5 foreach
5.6 try, catch

Closure
– closure must be declared with a space after the function keyword, and a space before and after the use keyword
– the opening brace must go on the same line, and the closing brace must go on the next line following the body
– there must not be a space after the opening parenthesis of the argument list or variable list, and there must not be a space before the closing parenthesis of the argument list or variable list
– in the argument list and variable list, there must not be a space before each comma, and there must be one space after each comma
– closure arguments with default value must go at end of the argument list

ああ、なんかすげー疲れた。。

php explode function to split character string

The explode function divides a character string into an array by the specified delimiter.

$gold = "カンガルー金貨,ウィーン金貨ハーモニー,メイプルリーフ金貨";
var_dump(explode(",",$gold));
echo  "<br>";

$invest ="地金;金貨;金証券;金鉱株";
var_dump(explode(";",$invest));

It seems easy to use CSV comma separated etc, isn’t it?

php strip_tags($value);

strip_tags -> Remove HTML and PHP tags from string
The optional second argument allows you to specify a tag that should not be removed.

$value = "<p>賃貸マンションやマンスリーマンション・賃貸アパートの情報を豊富に取り揃えておりますので、あなたの<b>希望にピッタリの賃貸物件</b>がみつかります。新生活や<a href='https:\/\/wwww.hogehoge.com'>一人暮らし</a>などの賃貸に関するご相談も受け付けております。</p>";

echo $value;
// echo strip_tags($value);

strip_tags();

$value = "<p>賃貸マンションやマンスリーマンション・賃貸アパートの情報を豊富に取り揃えておりますので、あなたの<b>希望にピッタリの賃貸物件</b>がみつかります。新生活や<a href='https:\/\/wwww.hogehoge.com'>一人暮らし</a>などの賃貸に関するご相談も受け付けております。</p>";

// echo $value;
echo strip_tags($value);

show time~♪

Regular Expression for Space Character Check

/[^\s ]/

Blank letters(\s) and double-byte spaces ( ) other than(^) are included.

– \s is a blank character abbreviation, including single-byte spaces, tabs, and new-line characters.
– The space after \s is full-width space
– Double-byte spaces are treated the same as Kanji, so the are not included in \s.
– Brackets([]) mean one character in parentheses. If there is no [], it will search for chunks of “\s”. If you use ^ outside of [], it means a different meaning.

$value = "富士山 が良く見える";

if (preg_match('/[^\s ]+$/u', $value)){
	echo "スペースが含まれています";
} else {
	echo "スペースが含まれていません";
}

What? Something is not working well.

禁則文字とは?

A character that comes inappropriate or difficult to read when it comes to the beginning of a line or at the end of a line. Representative examples include punctuation marks and parentheses. There are two kinds of prohibited character and the end-of-line prohibition character. The former refers to characters that you are having trouble coming up at the beginning of the line, and the latter refers to characters that you do not have trouble coming to the end of the line.

The following escape sequences are available.

\n 改行
\r キャリッジリターン
\t タブ
\\ \文字
\$ $文字
\( 左括弧
\) 右括弧
\[ 左括弧
\/ 右括弧
\' シングルクオテーション
\" ダブルクオテーション
\nnn 8進数表記
\xnn 16進数表記

Half-size check with regular expression

Half-size check with regular expression
Represent other than half-width characters in [^…] part.

$value = "こんにちは";

echo preg_match('/^[^ -~。-°\x00-\x1f\t]+$/u', $value);

[vagrant@localhost tests]$ ls
index.php
[vagrant@localhost tests]$ php -S 192.168.35.10:8000
PHP 7.1.21 Development Server started at Fri Feb 8 20:56:23 2019
Listening on http://192.168.35.10:8000
Document root is /home/vagrant/local/app/tests
Press Ctrl-C to quit.
[Fri Feb 8 20:56:31 2019] PHP Warning: preg_match(): Compilation failed: range out of order in character class at offset 11 in /home/vagrant/local/app/tests/index.php on line 5

なに? 修正します。

$value = "123";

if (preg_match('/^[^ -~。-゚\x00-\x1f\t]+$/u', $value)){
	echo "yes";
} else {
	echo "半角です";
}

/u
→ UTF-8 character code

OK

Perform a simple test with PHPUnit

I already tried installing PHPUnit, so I will try simple samples.

message.php

class Message
{
	private $message;
	public function __construct(string $message){
		$this->message = $message;
	}

	public function get(){
		return $this->message;
	}
}

messageTest.php

require_once ('../vendor/autoload.php');
require_once (dirname(__FILE__) .'../src/message.php');

use PHPUnit\Framework\TestCase;

class MessageTest extends TestCase{
	public function testGet(){
		$message = new Message('hello, world');
		$this->assertEquals('hello, world', $message->get());
	}
}

command line
[vagrant@localhost app]$ vendor/bin/phpunit tests
PHP Warning: require_once(../vendor/autoload.php): failed to open stream: No such file or directory in /home/vagrant/local/app/tests/messageTest.php on line 3
PHP Fatal error: require_once(): Failed opening required ‘../vendor/autoload.php’ (include_path=’.:/usr/share/pear:/usr/share/php’) in /home/vagrant/local/app/tests/messageTest.php on line 3

fix

require_once ('./vendor/autoload.php');
require_once ('./src/message.php');

use PHPUnit\Framework\TestCase;

class MessageTest extends TestCase{
	public function testGet(){
		$message = new Message('hello, world');
		$this->assertEquals('hello, world', $message->get());
	}
}

[vagrant@localhost app]$ vendor/bin/phpunit tests
PHPUnit 7.1.4 by Sebastian Bergmann and contributors.

. 1 / 1 (100%)

Time: 35 ms, Memory: 4.00MB

OK (1 test, 1 assertion)

ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh^^